Regex exactly n OR m times

FThompson picture FThompson · Dec 14, 2012 · Viewed 88.6k times · Source

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

Mark Byers picture Mark Byers · Dec 14, 2012

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.