# 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?

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`.

Here is the complete list of quantifiers (ref. http://www.regular-expressions.info/reference.html):

• `?`, `??` - 0 or 1 occurences (`??` is lazy, `?` is greedy)
• `*`, `*?` - any number of occurences
• `+`, `+?` - at least one occurence
• `{n}` - exactly `n` occurences
• `{n,m}` - `n` to `m` occurences, inclusive
• `{n,m}?` - `n` to `m` occurences, lazy
• `{n,}`, `{n,}?` - at least `n` occurence

To get "exactly N or M", you need to write the quantified regex twice, unless m,n are special:

• `X{n,m}` if `m = n+1`
• `(?:X{n}){1,2}` if `m = 2n`
• ...

No, there is no such quantifier. But I'd restructure it to `/X{m}(X{m-n})?/` to prevent problems in backtracking.