patterncsharpCritical
Regex for numbers only in C#
Viewed 0 times
regexnumbersonlyfor
Problem
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 two examples below it is matching a string that contains all numbers plus an equals sign like "1234=4321". I'm sure there's a way to change this behavior, but as I said, I've never really done much with regular expressions.
In case it matters, I'm using C# and .NET2.0.
string compare = "1234=4321";
Regex regex = new Regex(@"[\d]");
if (regex.IsMatch(compare))
{
//true
}
regex = new Regex("[0-9]");
if (regex.IsMatch(compare))
{
//true
}
In case it matters, I'm using C# and .NET2.0.
Solution
Use the beginning and end anchors.
Use
Note that
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.
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.
Code Snippets
Regex regex = new Regex(@"^\d$");Context
Stack Overflow Q#273141, score: 625
Revisions (0)
No revisions yet.