There's no specific syntax for that, but there are lots of ways to do it:
(?:\d{4}|\d{2}) <-- alternation: four digits if possible, else just two
\d{2}(?:\d{2})? <-- two digits, plus two more if possible
(?:\d{2}){1,2} <-- two digits, times one or two
So, for example, to match strings consisting of one or more letters A–Z followed by either two or four digits, you might write ^[A-Z]+(?:\d{4}|\d{2})$
; and to match a comma-separated list of two-or-four-digit numbers, you might write ^((?:\d{4},|\d{2},)*(?:\d{4}|\d{2})$
or ^(?:\d{2}(?:\d{2})?,)*\d{2}(?:\d{2})$
.
abc 123 xyz
? Should it match12
because that is exactly two digits in sequence? Or should it not, because12
is part of a larger digit sequence123
which itself is neither 2 nor 4 long? If I had to guess, I'd think you want the latter behaviour, but it isn't clear from your question. Examples and/or a clearer specification would help. Same question forabc 12345 def
... what should happen there?