Regex for numbers only
Solution 1:
Use the beginning and end anchors.
Regex regex = new Regex(@"^\d$");
Use "^\d+$"
if you need to match more than one digit.
Note that "\d"
will match [0-9]
and other digit characters like the Eastern Arabic numerals ٠١٢٣٤٥٦٧٨٩
. Use "^[0-9]+$"
to restrict matches to just the Arabic numerals 0 - 9.
If you need to include any numeric representations other than just digits (like decimal values for starters), then see @tchrist's comprehensive guide to parsing numbers with regular expressions.
Solution 2:
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).
Solution 3:
If you need to tolerate decimal point and thousand marker
var regex = new Regex(@"^-?[0-9][0-9,\.]+$");
You will need a "-", if the number can go negative.
Solution 4:
It is matching because it is finding "a match" not a match of the full string. You can fix this by changing your regexp to specifically look for the beginning and end of the string.
^\d+$
Solution 5:
Perhaps my method will help you.
public static bool IsNumber(string s)
{
return s.All(char.IsDigit);
}