a coder
a coder

Reputation: 7639

Limiting number of matched digits in regex

I need to match series of digits between 5 and 7 characters long. I thought this would do the trick:

([0-9]{5,7})\w+

against this string:

Sample text for testing:  22 333 4444 55555 666666 7777777 

As you can see in the regexr example it does not match digits having 5 numbers, and matches digits longer than 7 numbers long.

Why isn't this working like I expect?

Upvotes: 0

Views: 57

Answers (2)

Andie2302
Andie2302

Reputation: 4887

The regex ([0-9]{5,7})\w+ doesnt't work as expected, because:

example-string: 12345

([0-9]{5,7})\w+
    ^ Matches the digits: 12345

([0-9]{5,7})\w+
             ^ Cannot match a word character (letter, digit, underscore)

example-string: 123456789

([0-9]{5,7})\w+
    ^ Matches the digits: 1234567

([0-9]{5,7})\w+
             ^ Matches the digits: 89

To match a number with 5 to 7 digits use:

\b\d{5,7}\b

\b ....... matches at the beginning or end of a word.
\d{5,7}... matches a digit in the range of 0-9 between 5 and 7 times.

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

it does not match digits having 5 numbers, and matches digits longer than 7 numbers long.

Note that the following \w+ would also match the digits. ([0-9]{5,7})\w+ expects 5,6,7 digits plus at-least a single word character. But there isn't a word character exist just after to 55555 . So it fails to match 55555 on your input string.

Upvotes: 2

Related Questions