简体   繁体   English

PHP Regex随机匹配4位数字和2个字母

[英]PHP Regex match 4 digits and 2 letters in random order

I'm trying to create regex, which will match 4 digits and 2 letters in any order. 我正在尝试创建正则表达式,它将以任意顺序匹配4位数字和2个字母。 Letters can be in lower and upper cases. 字母可以大小写。

Example: 例:

a1234B
17AF45
aR1307

Any advice would be appreciated. 任何意见,将不胜感激。 Thanks. 谢谢。

A brute force approach to this might be to just use two positive lookaheads: 蛮力的解决方法可能是只使用两个积极的前瞻:

^(?=.*[A-Za-z].*[A-Za-z])(?=.*\d.*\d.*\d.*\d).{6}$

This would match exactly two letters, lowercase or uppercase, and four digits, for a total of six characters. 这将完全匹配两个字母(小写或大写)和四个数字,总共六个字符。

Demo 演示

For a deeper explanation, consider the first lookahead: 有关更深入的解释,请考虑以下先行内容:

^(?=.*[A-Za-z].*[A-Za-z])

This says to assert (but not match) from the start of the string that two letters occur anywhere in the string. 这表示从字符串开头断言 (但不匹配)两个字母出现在字符串中的任何位置。 Assuming this is true, then the regex engine will evaluate the next lookahead, which checks for four numbers. 假设这是真的,那么正则表达式引擎将评估下一个前瞻,该前瞻将检查四个数字。 If that also be true, then all that is needed is to match any 6 characters. 如果也是如此,那么只需匹配任意6个字符。 Those matching characters must only letters and numbers, due to the lookaheads. 由于前瞻性,那些匹配的字符只能是字母和数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM