且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正则表达式用于字符串中至少一定数量的数字

更新时间:2023-02-19 11:22:19

以下内容将匹配至少包含 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.