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} - 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
  • ...

Solution 3:

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