首页 > 解决方案 > 无特定顺序的字符和数字的正则表达式(但最多 10 个数字)

问题描述

所以我有一个字符串(带空格):

John Doe

最多可以混合 10 个数字

John Doe 123456789

没有特别的顺序:

1234john Doe567890

我试过像这样混合字符、空格和数字:

([A-Za-z ])([0-9]){10}

但我没有击中目标

我如何编写正则表达式来验证这一点?

标签: regex

解决方案


尝试这个

^(?=(?:\D*\d){0,10}\D*$)  

解释:

 ^                   # Beginning of string, BOS

 # Lookahead assertion
 (?=
      # Note this group is designed 
      # so that it is the only place
      # a digit can exist.

      (?:                 # Group
           \D*                 #  Optional, any amount of non-digits
           \d                  #  Required, a single digit
      ){0,10}             # End group, do 0 to 10 times

      # Example:
      #   - If this group runs 0 times, no digits were in the string.
      #   - If this group runs 4 times, 4 digits are in the string.
      #   - Therefore, min digits = 0, max digits = 10

      \D*                 # Finally, and optionally, any amount of non-digits
      $                   # End of string, EOS
 )

推荐阅读