T. Junghans
T. Junghans

Reputation: 11683

How can this regular expression be modified to detect and ignore too many characters?

I have the following string which I am trying to parse with a regex:

"id=12345,123456,1234567"

The string is part of a hash value and can appear in one of the following ways:

"#id=12345" // single value
"#id=12345,123456,1234567" // multiple values
"#id=12345,123456,1234567&Another=Value" // one or more values followed by an ampersand.

Only numbers with 5 or 6 characters are valid, so the result should be an array like below:

['12345', '123456']

This is the regex I currently have but it also includes the 7-digit number (last one above):

"id=12345,123456,1234567".match(/([0-9]{5,6})+/g); 

Resulting in:

["12345", "123456", "123456"] // Should only have two items

What can I do to prevent numbers larger then 6 digits?

Upvotes: 3

Views: 58

Answers (1)

Jerry
Jerry

Reputation: 71538

Easiest would be to use word boundaries:

/(\b[0-9]{5,6}\b)+/g

And I'm not sure why you're using the + quantifier here...

/\b[0-9]{5,6}\b/g

That should be enough.

Word boundaries match in between \w\W, \W\w, \w$ and ^\w by the way.

Upvotes: 5

Related Questions