Regex that accepts only numbers (0-9) and NO characters

mo alaz picture mo alaz · Oct 31, 2013 · Viewed 891.1k times · Source

I need a regex that will accept only digits from 0-9 and nothing else. No letters, no characters.

I thought this would work:

^[0-9]

or even

\d+

but these are accepting the characters : ^,$,(,), etc

I thought that both the regexes above would do the trick and I'm not sure why its accepting those characters.

EDIT:

This is exactly what I am doing:

 private void OnTextChanged(object sender, EventArgs e)
    {

   if (!System.Text.RegularExpressions.Regex.IsMatch("^[0-9]", textbox.Text))
        {
            textbox.Text = string.Empty;
        }
    }

This is allowing the characters I mentioned above.

Answer

Michael Liu picture Michael Liu · Oct 31, 2013

Your regex ^[0-9] matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $ to the end:

^[0-9]*$

This accepts any number of digits, including none. To accept one or more digits, change the * to +. To accept exactly one digit, just remove the *.

UPDATE: You mixed up the arguments to IsMatch. The pattern should be the second argument, not the first:

if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))

CAUTION: In JavaScript, \d is equivalent to [0-9], but in .NET, \d by default matches any Unicode decimal digit, including exotic fare like ႒ (Myanmar 2) and ߉ (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9] (or supply the RegexOptions.ECMAScript flag).