[英]Regex for at least a certain number of digits in a string
When a user submits a form I need to make sure that the input contains at least a minimum number of digits. 用户提交表单时,我需要确保输入内容至少包含最小位数。 The problem is that I don't know what format the input will be in. The digits likely won't be in a row, and might be separated by letters, punctuation, spaces, etc. I don't care about the rest of the string. 问题是我不知道输入将采用哪种格式。数字可能不会连续出现,并可能由字母,标点符号,空格等分隔。我不在乎其余的数字字符串。
I'd like to check this with a RegularExpressionValidator but I'm not quite sure how to write the regex. 我想用RegularExpressionValidator进行检查,但是我不太确定如何编写正则表达式。
I guess this would be similar to a phone number regex, but a phone number at least has some common formats. 我想这将类似于电话号码正则表达式,但电话号码至少具有某些常见格式。
The following will match an input string containing at least n
digits: 以下将匹配至少包含n
数字的输入字符串:
Regex.IsMatch(input, @"(\D*\d){n}");
where n
is an integer value. 其中n
是整数值。
A short explanation: 简短说明:
\\D*
matches zero or more non-digit chars ( \\D
is a short hand for [^0-9]
or [^\\d]
); \\D*
匹配零个或多个非数字字符( \\D
是[^0-9]
或[^\\d]
的简写); \\D*\\d
matches zero or more non-digit chars followed by a digit; 因此\\D*\\d
匹配零个或多个非数字字符,后跟一个数字; (\\D*\\d){n}
groups, and repeats, the previous n
times. 和(\\D*\\d){n}
分组并重复前n
次。 I would approach it something like this: 我会这样处理:
Regex.IsMatch(input, @"^([^0-9]*[0-9]){10}.*$");
In words, this would search for 10 digits, each of which are surrounded by 0 or more characters. 换句话说,这将搜索10个数字,每个数字都被0个或多个字符包围。 Since the .* are greedy, any additional digits would be matched by them as well. 由于。*是贪婪的,因此任何其他数字也将由它们匹配。
Anyway, check out http://regexlib.com/RETester.aspx It can be really hard to write a regular expression without something to test against. 无论如何,请访问http://regexlib.com/RETester.aspx。如果没有要测试的东西,编写正则表达式真的很难。
in order to have at least n digits, you need to use following regex: 为了至少有n位数字,您需要使用以下正则表达式:
(\\D*\\d){n,} (\\ D * \\ d){n,}
Regex (\\D*\\d){n} will match exactly n digits. 正则表达式(\\ D * \\ d){n}将精确匹配n个数字。
Regards, Karlo. 问候,卡洛。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.