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
This works with integers and decimal numbers. It doesn't match if the number has the coma thousand separator ,
"^-?\\d*(\\.\\d+)?$"
some strings that matches with this:
894
923.21
76876876
.32
-894
-923.21
-76876876
-.32
some strings that doesn't:
hello
9bye
hello9bye
888,323
5,434.3
-8,336.09
87078.
^\d+$, which is "start of string", "1 or more digits", "end of string" in English.
I think that this one is the simplest one and it accepts European and USA way of writing numbers e.g. USA 10,555.12 European 10.555,12 Also this one does not allow several commas or dots one after each other e.g. 10..22 or 10,.22 In addition to this numbers like .55 or ,55 would pass. This may be handy.
^([,|.]?[0-9])+$
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.
Perhaps my method will help you.
public static bool IsNumber(string s)
{
return s.All(char.IsDigit);
}
If you want to extract only numbers from a string the pattern "\d+" should help.