Problem
I’ve never worked with regular expressions before, so I’m having issues debugging. I want the regex to match only when the contained string consists entirely of numbers; but, in the two examples below, it matches a string that consists entirely of numbers plus an equals sign, such as “1234=4321.” I’m sure there’s a method to adjust this behavior, but as I previously stated, I’ve never worked with regular expressions very much.
string compare = "1234=4321";
Regex regex = new Regex(@"[\d]");
if (regex.IsMatch(compare))
{
//true
}
regex = new Regex("[0-9]");
if (regex.IsMatch(compare))
{
//true
}
I’m using C# and.NET2.0, in case that matters.
Asked by Timothy Carter
Solution #1
Use the anchors at the start and conclusion of your sentence.
Regex regex = new Regex(@"^\d$");
Use “^\d+$” if you need to match more than one digit.
It’s worth noting that “d” will match [0-9] and other digit characters, such as Eastern Arabic numerals. To limit matches to to the Arabic digits 0 – 9, use “[0-9]+$.”
See @tchrist’s full guide to parsing numbers with regular expressions if you need to include any numeric representations other than digits (for example, decimal values).
Answered by Bill the Lizard
Solution #2
Because your regex will match anything with a number, you’ll want to use anchors to match the entire string before matching one or more numbers:
regex = new Regex("^[0-9]+$");
The & will anchor the string’s beginning, the $ will anchor the string’s end, and the + will match one or more of the characters before it (a number in this case).
Answered by Robert Gamble
Solution #3
If you can live with a decimal point and a thousand marker,
var regex = new Regex(@"^-?[0-9][0-9,\.]+$");
If the number may go negative, you’ll need a “-.”
Answered by Andrew Chaa
Solution #4
It’s matching because it’s looking for “a match,” not a full string match. You can address this by altering your regexp to look for the beginning and end of the string specifically.
^\d+$
Answered by kasperjj
Solution #5
Perhaps my way will be of assistance to you.
public static bool IsNumber(string s)
{
return s.All(char.IsDigit);
}
Answered by Raz Megrelidze
Post is based on https://stackoverflow.com/questions/273141/regex-for-numbers-only