14

I want to write a regular expression in C# that inputs only a specific number of only numbers.

Like writing a regular expression to validate 5 digits number like so "12345"

2
  • 3
    Please show us your own attempt. Stackoverflow is not here to do your work for you, but to help you with your own efforts when you're stuck. Commented May 4, 2013 at 11:44
  • 1
    msdn.microsoft.com/en-us/library/az24scfc.aspx Commented May 4, 2013 at 11:44

3 Answers 3

47

Use the following regex with Regex.IsMatch method

^[0-9]{5}$ 

^ and $ will anchors the match to the beginning and the end of the string (respectively) to prevent a match to be found in the middle of a long string, such as 1234567890 or abcd12345efgh.

[0-9] indicates a character class that specifies a range of characters from 0 to 9. The range is defined by the Unicode code range that starts and ends with the specified characters. The {5} followed behind is a quantifier indicating to repeat the [0-9] 5 times.

Note that the solution of ^\d{5}$ is only equivalent to the above solution, when RegexOptions.ECMAScript is specified, otherwise, it will be equivalent to \p{Nd}, which matches any Unicode digits - here is the list of all characters in Nd category. You should always check the documentation of the language you are using as to what the shorthand character classes actually matches.

I strongly suggest that you read through the documentation. You can use other resources, such as http://www.regular-expressions.info/, but always check back on the documentation of the language that you are using.

Sign up to request clarification or add additional context in comments.

Comments

6

You can specify the number of repetitions in braces as in:

\d{5} 

If you want your whole input match a pattern enclose them in ^ and $:

^\d{5}$ 

4 Comments

And it will not just match 0-9 digits. It will also match other Unicode digits
@m.buettner No it matches only 5 digits. More digits may be returned in another match. However if OP intends to make sure the whole input consists of 5 digits he can use ^ and $ that I reflected in my updated answer.
@nhahtdh OP is not specific to what kind of numbers he want to match.
It is important to notify such thing to the reader. It is not a consistent behavior in regex flavours.
0

This expression should pass

\d{5}[^\d]+ 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.