开发者

Regular Expression to validate Data

In our application we need to check if a given string has on开发者_StackOverflowly 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([a-z])\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.

Regular Expression to validate Data

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜