Sardaukar
Sardaukar

Reputation: 30904

Regular expression for matching numbers and ranges of numbers

In an application I have the need to validate a string entered by the user.

One number OR a range (two numbers separated by a '-') OR a list of comma separated numbers and/or ranges AND any number must be between 1 and 999999.

A space is allowed before and after a comma and or '-'.

I thought the following regular expression would do it.

(\d{1,6}\040?(,|-)?\040?){1,}

This matches the following (which is excellent). (\040 in the regular expression is the character for space).

However, I also get a match on:

What am I missing here?

Upvotes: 0

Views: 1086

Answers (2)

Vijay
Vijay

Reputation: 67211

/\d*[-]?\d*/

i have tested this with perl:

> cat temp
00001 
12 
20,21,22 
100-200 
1,2-9,11-12 
20, 21, 22 
100-200
1, 2-9, 11-12
> perl -lne 'push @a,/\d*[-]?\d*/g;END{print "@a"}' temp
00001   12   20  21  22   100-200   1  2-9  11-12   20   21   22   100-200  1   2-9   11-12 

As the result above shows putting all the regex matches in an array and finally printing the array elements.

Upvotes: 0

stema
stema

Reputation: 92976

You need to anchor your regex

^(\d{1,6}\040?(,|-)?\040?){1,}$

otherwise you will get a partial match on "!!!12", it matches only on the last digits.

See it here on Regexr

Upvotes: 1

Related Questions