Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for specific number of digits [closed]

Tags:

c#

regex

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"

like image 291
Muhammad Reda Avatar asked May 04 '13 11:05

Muhammad Reda


2 Answers

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.

like image 162
nhahtdh Avatar answered Oct 09 '22 21:10

nhahtdh


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}$
like image 27
Sina Iravanian Avatar answered Oct 09 '22 21:10

Sina Iravanian