tags:

views:

11129

answers:

6

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.

        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.

+20  A: 

Use the beginning and end anchors.

Regex regex = new Regex(@"^\d$");

Use "^\d+$" if you need to match more than one digit.

EDIT: Use "^[0-9]+$" to restrict matches to Arabic numerals.

Bill the Lizard
Realize that this solution will also match numbers outside the 0-9 range since Unicode defines more than just 10 numbers. See http://www.moserware.com/2008/02/does-your-code-pass-turkey-test.html
Jeff Moser
@Jeff Moser: Thanks, I edited my answer. I was not aware of this issue with the \d shorthand.
Bill the Lizard
+5  A: 

It is matching because it is finding "a match" not a match of the full string. You can fix this by changing your regexp to specifically look for the beginning and end of the string.

^\d+$
kasperjj
+3  A: 

Your regex will match anything that contains a number, you want to use anchors to match the whole string and then match one or more numbers:

regex = new Regex("^[0-9]+$");

The ^ will anchor the beginning of the string, the $ will anchor the end of the string, and the + will match one or more of what precedes it (a number in this case).

Robert Gamble
A: 

^\d+$, which is "start of string", "1 or more digits", "end of string" in English.

Mark Brackett
+3  A: 

Do you need to match numbers or digits? For example: 123.456 is a number, but it's not all digits.

Joel Coehoorn
Exactly, OP is not totally clear about using integers or not
Sune Rievers