I’m attempting to match a string that can contain any number of numeric characters or a decimal point using the following regex:
([0-9.])*
Here’s some C# code to test the regex:
Regex regex = new Regex("([0-9.])*");
if (!regex.IsMatch("a"))
throw new Exception("No match.");
I expect the exception to be thrown here but it isn’t – am I using the Regex incorrectly or is there an error in the pattern?
EDIT: I’d also like to match a blank string.
The
*quantifier means “match 0 or more”. In your case, “a” returns 0 matches, so the regex still succeeds. You probably wanted:The
+quantifier means “match 1 or more, so it fails on non-numeric inputs and returns no matches. A quick spin the regex tester shows:Looks like we have some false positives, let’s revise the regex as such:
Now we get:
Coolness.