Regex exactly n OR m times
Solution 1:
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
.
Solution 2:
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}
- exactlyn
occurences -
{n,m}
-n
tom
occurences, inclusive -
{n,m}?
-n
tom
occurences, lazy -
{n,}
,{n,}?
- at leastn
occurence
To get "exactly N or M", you need to write the quantified regex twice, unless m,n are special:
-
X{n,m}
ifm = n+1
-
(?:X{n}){1,2}
ifm = 2n
- ...
Solution 3:
No, there is no such quantifier. But I'd restructure it to /X{m}(X{m-n})?/
to prevent problems in backtracking.