Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the first set of 5 digits in a text

I need to find the first set of 5 numbers in a text like this :

;SUPER U CHARLY SUR MARNE;;;rte de Pavant CHARLY SUR MARNE Picardie 02310;Charly-sur-Marne;;;02310;;;;;;;;;;;;;;

I need to find the first 02310 only.

My regex but it found all set of 5 numbers :

([^\d]|^)\d{5}([^\d]|$)
like image 862
Laurent Avatar asked Jan 18 '26 07:01

Laurent


1 Answers

To match the first 5-digit number you may use

^.*?\K(?<!\d)\d{5}(?!\d)

See the regex demo. As you want to remove the match, simply keep the Replace With field blank. The ^ matches the start of a line, .*? matches any 0+ chars other than line break chars, as few as possible, and \K operator drops the text matched so far. Then, (?<!\d)\d{5}(?!\d) matches 5 digits not enclosed with other digits.

Another variation includes a capturing group/backreference:

Find What:      ^(.*?)(?<!\d)\d{5}(?!\d)
Replace With: $1

See this regex demo.

Here, instead of dropping the found text before the number, (.*?) is captured into Group 1 and $1 in the replacement pattern puts it back.

like image 140
Wiktor Stribiżew Avatar answered Jan 19 '26 21:01

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!