Regex exactly n OR m times

04/17/2020 23:00:02

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?

Verified Answer (88 Votes)

12/14/2012 13:10:58

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.

88

Answer #2 (60 Votes)

12/14/2012 13:16:33

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

Answer #3 (19 Votes)

12/14/2012 13:12:45

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

19
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.