I haven\'t used regular expressions at all, so I\'m having difficulty troubleshooting. I want the regex to match only when the contained string is all numbers; but with the
Sorry for ugly formatting. For any number of digits:
[0-9]*
For one or more digit:
[0-9]+
Another way: If you like to match international numbers such as Persian or Arabic, so you can use following expression:
Regex = new Regex(@"^[\p{N}]+$");
To match literal period character use:
Regex = new Regex(@"^[\p{N}\.]+$");
Your regex will match anything that contains a number, you want to use anchors to match the whole string and then match one or more numbers:
regex = new Regex("^[0-9]+$");
The ^
will anchor the beginning of the string, the $
will anchor the end of the string, and the +
will match one or more of what precedes it (a number in this case).
Regex for integer and floating point numbers:
^[+-]?\d*\.\d+$|^[+-]?\d+(\.\d*)?$
A number can start with a period (without leading digits(s)), and a number can end with a period (without trailing digits(s)). Above regex will recognize both as correct numbers.
A . (period) itself without any digits is not a correct number. That's why we need two regex parts there (separated with a "|").
Hope this helps.
If you need to check if all the digits are number (0-9) or not,
^[0-9]+$
1425 TRUE
0142 TRUE
0 TRUE
1 TRUE
154a25 FALSE
1234=3254 FALSE
Use beginning and end anchors.
Regex regex = new Regex(@"^\d$");
Use "^\d+$"
if you need to match more than one digit.