![](/img/trans.png)
[英]RegEx with fluent validation in C# - how to not allow spaces and certain special characters in a password?
[英]How to make this regex allow spaces c#
我有一个带有以下正则表达式的电话号码字段:
[RegularExpression(@"^[0-9]{10,10}$")]
这个检查输入正好是10个数字字符,我应该如何更改此正则表达式以允许空格使以下所有示例都有效
1234567890
12 34567890
123 456 7890
干杯!
这有效:
^(?:\s*\d\s*){10,10}$
说明:
^ - start line
(?: - start noncapturing group
\s* - any spaces
\d - a digit
\s* - any spaces
) - end noncapturing group
{10,10} - repeat exactly 10 times
$ - end line
如果您必须忽略任何其他字符,这种构造此正则表达式的方式也是相当可扩展的。
根据您的问题,您可以考虑使用Match Evaluator委托,如http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator.aspx中所述。
这将使计算数字和/或空格的问题变得简短
使用这个简单的正则表达式
var matches = Regex.Matches(inputString, @"([\\s\\d]{10})");
编辑
var matches = Regex.Matches(inputString, @"^((?:\s*\d){10})$");
说明:
^ the beginning of the string
(?: ){10} group, but do not capture (10 times):
\s* whitespace (0 or more times, matching the most amount possible)
\d digits (0-9)
$ before an optional \n, and the end of the string
这样的东西我认为^\\d{2}\\s?\\d\\s?\\d{3}\\s?\\d{4}$
有变体:10位数字或2位数字空格8位数字或3位数字空格3位数字空格4位数。
但是,如果你只想要这三种变体,可以使用这样的东西
^(?:\d{10})|(?:\d{2}\s\d{8})|(?:\d{3}\s\d{3}\s\d{4})$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.