简体   繁体   English

正则表达式以验证数据

[英]Regular Expression to validate Data

In our application we need to check if a given string has only numbers and is of length 8 . 在我们的应用程序中,我们需要检查给定的字符串是否只有数字并且长度为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. 3个人以3种方式回答了部分错误。 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 :-) ). 因为您可以认为自己知道它们的工作原理,然后它们才会咬您的^a([az])\\1$ (这对了解正则表达式的人来说是个玩笑:-))。

The regex is ^[0-9]{8}$ . 正则表达式为^[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 ). 您不要使用花式\\d ,因为.NET Regex认为它与09E6 ENG BENGALI DIGIT ZERO(非欧洲数字)匹配,除非您激活了其ECMA模式( RegexOptions.ECMAScript )。 Javascript with \\d means only 0-9 digits. \\d Javascript仅表示0-9位数字。 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" ) 并且,如果您真的想使用\\d ,请记住转义\\或在字符串之前加上逐字字符串文字符号( @"something"

^[0-9]{8}$ ^ [0-9] {8} $

Simple and clean. 简单干净。 You set the acceptable value range, inside the ['s, and the number of hits inside the {'s. 您可以在['s内设置可接受的值范围,并在{'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. ^和$指定字符串的开头和结尾,以确保您不匹配包含8个数字的字符串部分,如Xanatos所说。

Have you ever tried FilteredTextBox Demonstration in Ajax Control Toolkit? 您是否曾经在Ajax Control Toolkit中尝试过FilteredTextBox Demonstration

It's pretty cool. 它太酷了。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM