James Cadd
James Cadd

Reputation: 12216

C# Regex.IsMatch returns true when it shouldn't?

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.

Upvotes: 6

Views: 42698

Answers (3)

Alex Zinchenko
Alex Zinchenko

Reputation: 91

You should use + instead of *

Regex reg = new Regex("([0-9.])+");

This should work fine.

When you use * any string can match this pattern in your case.

Upvotes: 9

Juliet
Juliet

Reputation: 81516

The * quantifier means "match 0 or more". In your case, "a" returns 0 matches, so the regex still succeeds. You probably wanted:

([0-9.]+)

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:

input      result
-----      ------
[empty]    No matches
a          No matches
.          1 match: "."
20.15      1 match: "20.15"
1          1 match: "1"
1.1.1      1 match: "1.1.1"
20.        1 match: "20."

Looks like we have some false positives, let's revise the regex as such:

^([0-9]+(?:\.[0-9]+)?)$

Now we get:

input      result
-----      ------
[empty]    No matches
a          No matches
.          No matches
20.15      1 match: "20.15"
1          1 match: "1"
1.1.1      No matches: "1.1.1"
20.        No matches

Coolness.

Upvotes: 13

user166390
user166390

Reputation:

Regex.IsMatch("a", "([0-9.])*") // true

This is because the group can match ZERO or more times.

Regex.IsMatch("a", "([0-9.])+") // false

Upvotes: 12

Related Questions