1

Currently I have the following regular expression that matches 8 digits alphanumeric, I want to modify it such that it has to start with the number 2 and contains at least 2 numbers in this 8 digit. How can I do so?

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

2 回答 2

4

怎么样:

/^(?=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
----------------------------------------------------------------------
于 2013-09-13T07:54:28.503 回答
1

很容易让它从2开始,只要在开头加上:

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

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

于 2013-09-13T03:33:55.543 回答