I can\'t figure out how to construct a regex for the example values:
123,456,789
-12,34
1234
-8
Could you help me?
Try this:
^-?\d{1,3}(,\d{3})*(\.\d\d)?$|^\.\d\d$
Allows for:
1
12
.99
12.34
-18.34
12,345.67
999,999,999,999,999.99
For the examples:
^(-)?([,0-9])+$
It should work. Implement it in whichever language you want.
Try this:
^-?[\d\,]+$
It will allow an optional -
as the first character, and then any combination of commas and digits.
Since this question has been reopened four years later, I'd like to offer a different take. As someone spends a lot of time working with regex, my view is this:
A. If Possible, Don't Use Regex To Validate Numbers
If at all possible, use your language. There may be functions to help you determine if the value contained by a string is a valid number. That being said, if you're accepting a variety of formats (commas, etc.) you may not have a choice.
B. Don't Write the Regex Manually to Validate a Number Range
C. Spend your Regex Energy Wisely: Use Tools
For tools, you can use:
RegexMagic
(not free) by regex guru Jan Goyvaerts. It's his beginner regex product, and as I recall it has a great range of options for generating numbers in a given range, among other features. |
D. An Exercise: Building a Regex for the Specs in the Question
These specs are quite wide... but not necessarily vague. Let's look at the sample values again:
123,456,789
-12,34
1234
-8
How do the first two values relate? In the first, the comma matches groups of powers of three. In the second, it probably matches the decimal point in a continental-European-style number format. That does not mean we should allow digits everywhere, as in 1,2,3,44
. By the same token, we shouldn't be restrictive. The regex in the accepted answer, for instance, will not match one of the requirements, 123,456,789
(see demo).
How do we build our regex to match the specs?
^
and $
to avoid submatches-?
(?:this|that)
:[1-9][0-9]*(?:,[0-9]+)?
[1-9][0-9]{1,2}(?:,[0-9]{3})+
The complete regex:
^-?(?:[1-9][0-9]*(?:,[0-9]+)?|[1-9][0-9]{1,2}(?:,[0-9]{3})+)$
See demo.
This regex does not allow European-style numbers starting with 0
, such as 0,12
. It's a feature, not a bug. To match those as well, a small tweak will do:
^-?(?:(?:0|[1-9][0-9]*)(?:,[0-9]+)?|[1-9][0-9]{1,2}(?:,[0-9]{3})+)$
See demo.