Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match at least n times but not more than m times

Tags:

regex

I want a regular expression that could match the string %*--- with at least 1 hyphen but the expression should not be matched if there are more than 3 hyphens. So far I have come up with /^%?\*{1}\s*(\- *){1,3}/ but it is still matching when the hyphens exceed 3.

I have also tried ? after the range {1,3} but its not meeting the requirement.

like image 884
Aditi Avatar asked Mar 15 '23 09:03

Aditi


2 Answers

Although it's often written as {min,max} in tutorials and references, the enumerated quantifier does not mean not more than max. If it sees three hyphens, -{1,3} will consume all three, but it doesn't care what the next character is (if there is one). It's just like all other quantifiers in this regard: it consumes as much as it can, then it hands control to the next part of the regex.

That's why the other responders suggested using an end anchor ($). If you can't use an anchor, or don't want to, you can use a negative lookahead instead:

/^%\*-{1,3}(?!-)/
like image 155
Alan Moore Avatar answered Apr 09 '23 09:04

Alan Moore


You need a $ at the end, and your regex can be greatly simplified:

/^%\*--?-?$/

See demo.

like image 33
Bohemian Avatar answered Apr 09 '23 10:04

Bohemian