Coder Perfect

[duplicate] Regex that takes only digits (0-9) and no characters


I’m looking for a regex that only accepts digits from 0 to 9 and nothing else. There are no letters or characters.

This seemed like a good idea at the time:


or even


However, these characters are accepted:,$,(,), and so on.

I expected both of the regexes to work, and I’m not sure why it’s accepting those characters.


That’s precisely what I’m doing:

 private void OnTextChanged(object sender, EventArgs e)

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

This allows the characters I described earlier to be used.

Asked by mo alaz

Solution #1

[0-9] matches anything that starts with a digit, including strings like “1A.” Add a $ at the end to avoid a partial match:


Any number of numbers is acceptable, including none. Change the * to + to accommodate one or more digits. Simply remove the * to accept only one digit.

UPDATE: The parameters to IsMatch were messed up. The second argument, not the first, should be the pattern:

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

CAUTION: While d in JavaScript corresponds to [0-9], in.NET, d matches any Unicode decimal digit by default, including exotic stuff like (Myanmar 2) and (N’Ko 9). Stick with [0-9] unless your program is prepared to cope with these characters (or supply the RegexOptions.ECMAScript flag).

Answered by Michael Liu

Post is based on