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

I need a regular expression that will only accept numbers from 0-9 and nothing more. No letters, no characters.

I thought this would work:

^[0-9] 

or even

 \d+ 

but they accept characters: ^, $, (,), etc.

I thought both of the above expressions would do the trick, and I'm not sure why it accepts these 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 allows you to use the characters mentioned above.

+81
c # regex
Oct 31 '13 at 19:44
source share
1 answer

Your regular expression ^[0-9] matches any value starting with a digit, including strings like "1A". To avoid a partial match, add $ to the end:

 ^[0-9]*$ 

It accepts any number of digits, including not a single one. To accept one or more digits, change the * value to + . To accept exactly one digit, simply delete * .

UPDATE: You have mixed up arguments with IsMatch . The template should be the second argument, not the first:

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

ATTENTION:. In JavaScript, \d equivalent to [0-9] , but in .NET, \d defaults to any Unicode decimal digit , including exotic tariffs such as 2 (Myanmar 2) and ߉ (N'Ko 9). If your application is not ready to deal with these characters, stick to [0-9] (or check the RegexOptions.ECMAScript flag).

+207
Oct 31 '13 at 19:48
source share



All Articles