Vulcan Vulcan - 5 months ago 9
PHP Question

Regex exactly n OR m times

Consider the following regular expression, where

X
is any regex.

X{n}|X{m}


This regex would test for
X
occurring exactly
n
or
m
times.

Is there a regex quantifier that can test for an occurrence
X
exactly
n
or
m
times?

Answer

There is no single quantifier that means "exactly m or n times". The way you are doing it is fine.

An alternative is:

X{m}(X{k})?

where m < n and k is the value of n-m.