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.
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}(?!-)/
You need a $
at the end, and your regex can be greatly simplified:
/^%\*--?-?$/
See demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With