如何用PHP制作一个只接受3-9个字母(大写)和5-50个数字的RegEx?
我不太擅长正则表达式。但这个不管用:
/[A-Z]{3,9}[0-9]{5,50}/例如,它与ABC12345匹配,但不匹配A12345BC。
有什么想法吗?
发布于 2014-05-02 10:44:38
这是一个经典的“密码验证”-type问题。对于这一点,“粗略的配方”是检查每个条件的展望,然后我们匹配所有。
^(?=(?:[^A-Z]*[A-Z]){3,9}[^A-Z]*$)(?=(?:[^0-9]*[0-9]){5,50}[^0-9]*$)[A-Z0-9]*$我会在下面解释这个,但这里有一个变化,我会留给你们去弄清楚。
^(?=(?:[^A-Z]*[A-Z]){3,9}[0-9]*$)(?=(?:[^0-9]*[0-9]){5,50}[A-Z]*$).*$让我们一个接一个地看第一个正则表达式。
[A-Z0-9]*匹配整个字符串(如果它仅由大写的ASCII字母和数字组成)。(感谢@TimPietzcker指出,我在方向盘上睡着了,因为我在开车时看到了一个点星。)看台是怎么工作的?
(?:[^A-Z]*[A-Z]){3,9}[^A-Z]*$)断言,在当前位置,即字符串的开头,我们能够匹配“任意数量的非大写字母,后面跟着一个大写字母”,3到9次。这确保了我们有足够的大写字母。请注意,{3,9}是贪婪的,因此我们将匹配尽可能多的大写字母。但是我们不想比我们希望的匹配得更多,所以在表达式被{3,9}量化之后,查找检查是否可以匹配“零或任何数字”的字符,这些字符不是大写字母,直到字符串的末尾用锚点$标记。
第二种展望以类似的方式工作。
要更深入地解释这一技术,您可能需要仔细阅读本页面中有关[医]雷吉猎犬的密码验证部分。
如果您感兴趣,下面是对该技术的象征性解释。
^ the beginning of the string
(?= look ahead to see if there is:
(?: group, but do not capture (between 3 and 9 times)
[^A-Z]* any character except: 'A' to 'Z' (0 or more times)
[A-Z] any character of: 'A' to 'Z'
){3,9} end of grouping
[^A-Z]* any character except: 'A' to 'Z' (0 or more times)
$ before an optional \n, and the end of the string
) end of look-ahead
(?= look ahead to see if there is:
(?: group, but do not capture (between 5 and 50 times)
[^0-9]* any character except: '0' to '9' (0 or more times)
[0-9] any character of: '0' to '9'
){5,50} end of grouping
[^0-9]* any character except: '0' to '9' (0 or more times)
$ before an optional \n, and the end of the string
) end of look-ahead
[A-Z0-9]* any character of: 'A' to 'Z', '0' to '9' (0 or more times)
$ before an optional \n, and the end of the string发布于 2014-05-02 10:55:16
这是你的问题吗?http://regexr.com/38pn0
如果是这样,则需要将表达式锚定在字符串的开头和结尾:
/^[A-Z]{3,9}[0-9]{5,50}$/结果:http://regexr.com/38pmt (不匹配)
https://stackoverflow.com/questions/23426162
复制相似问题