Why does this Regex not work 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 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?


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}$

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.


You need:

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

This reads as "1-5 digits, followed by any number of non-digit characters, followed by 5 digits." If you want at least 1 non-digit character, use D+ .

Your previous regex would match because ' King Drive 12 OH' would match .* and ' ' would match the single character [^0-9] .

链接地址: http://www.djcxy.com/p/86972.html

上一篇: 9]在.NET正则表达式中

下一篇: 为什么这个正则表达式不能正常工作?