Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this Regex not work Properly?

Tags:

regex

i have the Following Regex:

 ^\d{1,5}.*[^0-9][0-9]{5}$

and the following text: 123 King Drive 12 OH 12345

i want to match the strings which start with a 1 to 5-digit number and end with a 5-digit number and have no other numbers between them. But i always get the whole text as a match although it should skip because of the 12 which is between 123 and 12345.

Why is this happening? shouldn't [^0-9] do the trick?

like image 244
fer y Avatar asked Dec 25 '22 23:12

fer y


2 Answers

Based on the description you make of your requirement, you seem to want this :

^\d{1,5}[^0-9]*[0-9]{5}$

The .* part was matching anything, so not excluding the digits.

like image 179
Denys Séguret Avatar answered Jan 13 '23 16:01

Denys Séguret


In your regex:

^\d{1,5}.*[^0-9][0-9]{5}$

And example text:

123 King Drive 12 OH 12345

--

^\d{1,5} is matching "123"

.* is matching " King Drive 12 OH"

[^0-9] is matching " "

[0-9]{5}$ is matching "12345"

As others have also suggested, something like this would avoid this issue, as you are explicitly saying (unlike by using ".*") not to match any non-digits in the middle of the string:

^\d{1,5}\D+\d{5}$
like image 23
Tom Lord Avatar answered Jan 13 '23 16:01

Tom Lord