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"
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.
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}$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With