正则表达式用于字符串中至少一定数量的数字 [英] Regex for at least a certain number of digits in a string

查看:68
本文介绍了正则表达式用于字符串中至少一定数量的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户提交表单时,我需要确保输入内容至少包含最小位数.问题是我不知道输入将采用哪种格式.数字可能不会连续出现,并可能由字母,标点符号,空格等分隔.我不在乎其余的数字字符串.

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.

我想用RegularExpressionValidator进行检查,但是我不太确定如何编写正则表达式.

I'd like to check this with a RegularExpressionValidator but I'm not quite sure how to write the regex.

我想这类似于电话号码正则表达式,但是电话号码至少具有某些常见格式.

I guess this would be similar to a phone number regex, but a phone number at least has some common formats.

推荐答案

以下内容将匹配至少包含 n 个数字的输入字符串:

The following will match an input string containing at least n digits:

Regex.IsMatch(input, @"(\D*\d){n}");

其中 n 是整数值.

简短说明:

  • \ D * 匹配零个或多个非数字字符( \ D [^ 0-9] 的简写,或 [^ \ d] );
  • 因此 \ D * \ d 匹配零个或多个非数字字符,后跟一个数字;
  • (\ D * \ d){n} 分组并重复以前的 n 次.
  • \D* matches zero or more non-digit chars (\D is a short hand for [^0-9] or [^\d]);
  • so \D*\d matches zero or more non-digit chars followed by a digit;
  • and (\D*\d){n} groups, and repeats, the previous n times.

这篇关于正则表达式用于字符串中至少一定数量的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆