fer y
fer y

Reputation: 525

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?

Upvotes: 4

Views: 162

Answers (4)

Tom Lord
Tom Lord

Reputation: 28305

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

Upvotes: 2

arshajii
arshajii

Reputation: 129507

The problem is .* which matches anything, what about

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

or more compactly

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

\D matches any non-digit. You can use \D* if you want to allow strings with nothing between the starting and ending digits.

Upvotes: 2

cmbuckley
cmbuckley

Reputation: 42458

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].

Upvotes: 2

Denys Séguret
Denys Séguret

Reputation: 382132

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.

Upvotes: 4

Related Questions