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

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

Asked on January 3, 2019 in Regex.
Add Comment

  • 1 Answer(s)

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


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


    Mixed up the arguments to IsMatch. The pattern is the second argument, not the first:

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

    Attention: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 our app is prepared to deal with these characters, stick with [0-9] or supply the RegexOptions.ECMAScript flag.

    Answered on January 3, 2019.
    Add Comment

  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.