正则表达式,其字符和数字没有特定的顺序(但最多10个数字)

时间:2019-03-08 18:43:39

标签: regex

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

John Doe

最多可以混合10个数字

John Doe 123456789

无特殊顺序:

1234john Doe567890

我已经尝试过像这样混合字符,空格和数字:

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

但是我没有击中目标

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

2 个答案:

答案 0 :(得分:2)

尝试

^(?=(?:\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
 )

答案 1 :(得分:0)

您可以使用

^(?:[A-Za-z ]*[0-9]){0,10}[A-Za-z ]*$

详细信息

  • ^-字符串的开头
  • (?:[A-Za-z ]*[0-9]){0,10}-零到十次出现
    • [A-Za-z ]*-0个或多个空格或字母
    • [0-9]-一个数字
  • [A-Za-z ]*-0个或多个空格或字母
  • $-字符串的结尾。

如果必须至少包含1位数字,请使用

^(?:[A-Za-z ]*[0-9]){1,10}[A-Za-z ]*$
                     ^