Regex pattern for capital letters and numbers only, with possible 'List'

Iain Ward picture Iain Ward · Jun 9, 2011 · Viewed 69.4k times · Source

What is the regex to match words that have the pattern:

Number or Capital in any order * 3 (+possible 'List' on the end)

For example,

OP3
G6H
ZZAList
349
127List

are all valid, whereas

a3G
P-0List
HYiList
def
YHr

are all invalid.

Answer

codaddict picture codaddict · Jun 9, 2011

You can use the regex:

^[A-Z0-9]{3}(?:List)?$

Explanation:

^        : Start anchor
[A-Z0-9] : Char class to match any one of the uppercase letter or digit
{3}      : Quantifier for previous sub-regex 
(?:List) : A literal 'List' enclosed in non-capturing paranthesis
?        : To make the 'List' optional
$        : End anchor

See it