Why is this regex not working properly?

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 strings starting with a 1 to 5-digit number and ending with a 5-digit number, and there are no other numbers between them. But I always get all the text as a coincidence, although it should skip because of 12 , which is between 123 and 12345 .

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

+4
source share
4 answers

In your regex:

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

And an example text:

 123 King Drive 12 OH 12345 

-

^ \ d {1,5} matches "123"

. * corresponds to "King Drive 12 OH"

[^ 0-9] matches ""

[0-9] {5} $ matches "12345"

Like others, they suggested that this could have avoided this problem, since you are explicitly saying (as opposed to using ". *") So as not to correspond to any signs in the middle of the line:

 ^\d{1,5}\D+\d{5}$ 
+2
source

Based on the description you make from your requirement, you seem to need this:

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

The .* Part was matched against anything, therefore not excluding the numbers.

+4
source

Problem .* That matches anything as regards

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

or more compact

 ^\d{1,5}\D+\d{5}$ 

\D matches any character. You can use \D* if you want to allow strings without anything between the leading and trailing digits.

+2
source

You need:

 ^\d{1,5}\D*\d{5}$ 

This reads as “1-5 digits followed by any number of digits without digits, and then 5 digits.” If you want at least 1 character without numbers, use \D+ .

Your previous regex will match because ' King Drive 12 OH' will match .* And ' ' will match a single character [^0-9] .

+2
source

Source: https://habr.com/ru/post/1493443/


All Articles