Question

I need to check if a textbox only contains whole numbers plus - and ,. Where - and , must only exist in between numbers, i.e. they must never exist at the end or at the starting.

The following would be valid

1-5,45,23,4,100-110

The following would be invalid

,1-4
-5-1,4

Can regex be used for such validation?

Was it helpful?

Solution

This should do:

^\d+(?:-\d+)?(?:,\d+(?:-\d+)?)*$

Explanation:

^          # Start of string  
\d+        # Match a number.
(?:-\d+)?  # Optionally match a dash and a number
(?:        # Match the following group:
 ,         #  a comma
 \d+       #  and a number
 (?:-\d+)? #  (or a range, as above)
)*         # any number of times, including zero.
$          # End of string

OTHER TIPS

The regex should do:

^(\d+(?:[-,]\d+)*)$

Online Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top