In our application we need to check if a given string has only numbers and is of length 8 . How can we specify this conditions in a regular expression ?
bool isValid = Regex.IsMatch("YourInput", @"^\d{8}$");
Is it so difficult to write this regex? 3 persons have responded in 3 ways that are partially wrong. This clearly shows why regexes shouldn't ever be used! Because you can think you know how they work, and then they'll bite your ^a([az])\\1$
(it's a joke for persons that know regexes :-) ).
The regex is ^[0-9]{8}$
. You anchor the regex with ^
and $
at the beginning and the end of the string. You don't use fancy \\d
, because the .NET Regex considers it to match 09E6 ০ BENGALI DIGIT ZERO (non european digits) unless you activate its ECMA mode ( RegexOptions.ECMAScript
). Javascript with \\d
means only 0-9 digits. And if you really really want to use \\d
, remember to escape the \\
or put a verbatim string literal sign before the string (the @"something"
)
^[0-9]{8}$
Simple and clean. You set the acceptable value range, inside the ['s, and the number of hits inside the {'s. ^ and $ to specify start and end of string, to make sure you don't match sections of strings, containing 8 numbers, as Xanatos says.
Have you ever tried FilteredTextBox Demonstration
in Ajax Control Toolkit?
It's pretty cool.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.