特定位数的正则表达式 [英] Regular expression for specific number of digits
问题描述
我想用C#编写一个仅输入特定数量的唯一数字的正则表达式.
I want to write a regular expression in C# that inputs only a specific number of only numbers.
就像编写正则表达式来验证5位数字一样,例如"12345"
Like writing a regular expression to validate 5 digits number like so "12345"
推荐答案
将以下正则表达式与 > Regex.IsMatch
方法
Use the following regex with Regex.IsMatch
method
^[0-9]{5}$
^
和 $
会将匹配项分别锚定到字符串的开头和结尾,以防止在长字符串的中间找到匹配项,例如 1234567890
或 abcd12345efgh
.
^
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]
表示字符类,它指定从 0
到 9
的字符范围.该范围由以指定字符开始和结束的Unicode代码范围定义.紧随其后的 {5}
是量化符,指示将 [0-9]
重复5次.
[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.
请注意,当它等效于 \ p {Nd}
,它匹配任何Unicode数字-这是
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.
我强烈建议您通读文档.您可以使用其他资源,例如 http://www.regular-expressions.info/,但始终查看所用语言的文档.
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.
这篇关于特定位数的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!