正则表达式匹配以数字 2 开头的 8 个字母数字,并且其中至少有两个数字


regular expression to match 8 alphanumeric starting with number 2 and at least has two number in it

目前我有以下与 8 位字母数字匹配的正则表达式,我想修改它,使其必须以数字 2 开头,并且在这 8 位数字中至少包含 2 个数字。我该怎么做?

preg_match('/[A-Za-z0-9]{8}/', $bio)

怎么样:

/^(?=2.*'d)[a-zA-Z0-9]{8}$/

如果数字2计入 2 个所需数字之一。

/^(?=2.*'d.*'d)[a-zA-Z0-9]{8}$/

如果数字2不计入 2 个所需数字之一。

解释:

The regular expression:
(?-imsx:^(?=2.*'d)[a-zA-Z0-9]{8}$)
matches as follows:
NODE                     EXPLANATION
----------------------------------------------------------------------
(?-imsx:                 group, but do not capture (case-sensitive)
                         (with ^ and $ matching normally) (with . not
                         matching 'n) (matching whitespace and #
                         normally):
----------------------------------------------------------------------
  ^                        the beginning of the string
----------------------------------------------------------------------
  (?=                      look ahead to see if there is:
----------------------------------------------------------------------
    2                        '2'
----------------------------------------------------------------------
    .*                       any character except 'n (0 or more times
                             (matching the most amount possible))
----------------------------------------------------------------------
    'd                       digits (0-9)
----------------------------------------------------------------------
  )                        end of look-ahead
----------------------------------------------------------------------
  [a-zA-Z0-9]{8}           any character of: 'a' to 'z', 'A' to 'Z',
                           '0' to '9' (8 times)
----------------------------------------------------------------------
  $                        before an optional 'n, and the end of the
                           string
----------------------------------------------------------------------
)                        end of grouping
----------------------------------------------------------------------

很容易让它以 2 开头,只需在开头添加它:

preg_match('/2[A-Za-z0-9]{7}/', $bio)

但是,正则表达式不适合第二个要求 - 确保至少有 2 位数字。您可以设计一个正则表达式来检查内部的两位数,但无法检查长度是否为 8。因此,您可以制作两个单独的正则表达式(一个用于长度,一个用于 2 位数字),或者逐个字符分别分析代码中的输入。