43

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.

08Dc91wk
  • 4,254
  • 8
  • 34
  • 67
Iain Ward
  • 9,850
  • 5
  • 34
  • 41

2 Answers2

79

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

codaddict
  • 445,704
  • 82
  • 492
  • 529
  • 6
    That works a treat, and thanks for including an explanation too, regex is starting to make more sense to me now. Though not by much... ;P – Iain Ward Jun 09 '11 at 08:52
0

A solution that works with diacritics on capital letters and with Eastern Arabic numerals:

^[[:upper:][:digit:]]{3}(?:List)?$

[:upper:] is a Posix class that matches all uppercase letters, including "É", "Ê", "Ç", "Ö" and so on. [:digit:] can also match numbers like ١٢٣.

See it

rturquier
  • 151
  • 7