我想验证一个电话号码。我的条件是,在给定的字符串中,我希望至少有7个数字,忽略分隔符,X,段落。
实际上,我想在regex中实现这个功能:
Func<string, bool> Validate = s => s.ToCharArray().Where(char.IsDigit).Count() >= 7;
Func<string, bool> RegexValidate = s => System.Text.RegularExpressions.Regex.IsMatch(s, @"regex pattern should come here.")
string x = "asda 1234567 sdfasdf";
string y = "asda sdfa 123456 sdfasdf";
bool xx = Validate(x); //true
bool yy = Validate(y); //false
我需要的目的是希望在asp:RegularExpressionValidator中包含此正则表达式
发布于 2009-07-13 08:02:15
七位或更多数字,与任意数量的任何其他类型的字符混合在一起?这似乎不是一个非常有用的需求,但现在你可以这样做了:
^\D*(?:\d\D*){7,}$
发布于 2009-07-13 08:12:37
为什么要使用正则表达式呢?您发布的第一个Validate
函数简单地计算了数字的数量,它更容易理解,而且可能也更快。我只需要去掉不必要的ToCharArray
调用,将谓词压缩到Count
函数中,然后就完成了:
s.Count(char.IsDigit) >= 7;
请注意,如果您只想接受'normal‘数字(即0-9),那么您需要更改验证函数,因为IsDigit
匹配许多不同的数字表示形式,例如
s.Count(c => c >= '0' && c <= '9') >= 7;
https://stackoverflow.com/questions/1118150
复制相似问题