Reputation: 5832
I created a regex to match numbers from 1-100, including decimals such as 50.25
For some reason, decimal numbers are not matching and I have no idea why.
Can someone help?
string pattern = @"^([1-9][0-9]{0,1}(\\.[\\d]{1,2})?|100)$";
Regex r = new Regex(pattern);
Match m = r.Match(s.SearchRadius);
if (!m.Success)
{
s.SearchRadius = "20";
}
Upvotes: 3
Views: 2442
Reputation: 28137
Just to play devils advocate - the non-regex solution is:
double d;
if (!(double.TryParse(s.SearchRadius, out d) && d <= 100 && d >= 0))
{
s.SearchRadius = "20";
}
And for good measure that famous quote by Jamie Zawinski:
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.
Upvotes: 2
Reputation: 378
Your code catches both the number xx.xx and .xx. If you want it to catch the number only once insert the ?: in the second parenthesis.
^([1-9][0-9]{0,1}(?:\.[\d]{1,2})?|100)$
Btw, a good way to test regular expressions is a site like http://rubular.com/ where u can see the results right away.
Upvotes: 0
Reputation: 17949
When using @""
string literals, you don't escape backslashes. You probably intended for \.
and \d
@"^([1-9][0-9]{0,1}(\.[\d]{1,2})?|100)$";
Upvotes: 4
Reputation: 4218
You're using the @
sign on your string, so you shouldn't escape \ characters.
All you need is
string pattern = @"^([1-9][0-9]{0,1}(\.[\d]{1,2})?|100)$";
Upvotes: 9