简体   繁体   中英

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. 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. Those matching characters must only letters and numbers, due to the lookaheads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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