目前我有以下正则表达式匹配8位数的字母数字,我想修改它,使其必须以数字2开头,并且在这8位数字中至少包含2个数字。我怎么能这样做?
preg_match('/[A-Za-z0-9]{8}/', $bio)
答案 0 :(得分: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
----------------------------------------------------------------------
答案 1 :(得分:1)
以2开头很容易,只需在开头添加它:
preg_match('/2[A-Za-z0-9]{7}/', $bio)
然而,正则表达式不适合第二个要求 - 确保至少有2位数。您可以设计一个检查内部两位数的正则表达式,但是无法检查长度为8.因此您要么制作两个单独的正则表达式(一个用于长度,一个用于2个数字)或分析输入逐个字符地编码。