C# 特定位数的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16373895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:52:45  来源:igfitidea点击:

Regular expression for specific number of digits

c#regex

提问by Muhammad Reda

I want to write a regular expression in C# that inputs only a specific number of only numbers.

我想在 C# 中编写一个正则表达式,只输入特定数量的数字。

Like writing a regular expression to validate 5 digits number like so "12345"

就像编写正则表达式来验证 5 位数字,例如“12345”

采纳答案by nhahtdh

Use the following regex with Regex.IsMatchmethod

将以下正则表达式与Regex.IsMatch方法一起使用

^[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 1234567890or abcd12345efgh.

^并将$匹配锚定到字符串的开头和结尾(分别)以防止在长字符串的中间找到匹配,例如1234567890or abcd12345efgh

[0-9]indicates a character class that specifies a range of characters from 0to 9. The range is defined by the Unicode code range that starts and ends with the specified characters. The {5}followed behind is a quantifierindicating to repeat the [0-9]5 times.

[0-9]表示指定从0到的字符范围的字符类9。该范围由以指定字符开始和结束的 Unicode 代码范围定义。该{5}身后跟着的是一个量词表明重复[0-9]5次。

Note that the solution of ^\d{5}$is only equivalent to the above solution, when RegexOptions.ECMAScriptis specified, otherwise, it will be equivalent to \p{Nd}, which matches any Unicode digits - here is the list of all characters in Ndcategory. You should always check the documentation of the language you are using as to what the shorthand character classes actually matches.

请注意, 的解决方案^\d{5}$仅等效于上述解决方案,当RegexOptions.ECMAScript指定时,否则将等效于\p{Nd},匹配任何 Unicode 数字 - 这里是category中所有字符的列表Nd。您应该始终检查您使用的语言的文档,以了解速记字符类实际匹配的内容。

I strongly suggest that you read through the documentation. You can use other resources, such as http://www.regular-expressions.info/, but alwayscheck back on the documentation of the language that you are using.

我强烈建议您通读文档。您可以使用其他资源,例如http://www.regular-expressions.info/,但请务必查看您正在使用的语言的文档。

回答by Sina Iravanian

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 $:

如果您希望整个输入匹配一个模式,请将它们括在^and 中$

^\d{5}$

回答by Uzzy

This expression should pass

这个表达式应该通过

\d{5}[^\d]+