Regex, That Matches No more Than n Occurrences

user6713148 picture user6713148 · Apr 3, 2017 · Viewed 9.9k times · Source

I'm trying to find a Regex, that matches no more than n consecutive, say three, for example, occurrences of a character; in the case of three and character is "a":
abbaa - matches;
ammaaa - doesn't match(three consecutive a's), there is one "a", but whole expression must be discarded because three "a's"

Thank you.

Answer

jakeehoffmann picture jakeehoffmann · Apr 3, 2017

Use the {m,n} syntax (if your environment provides it, which it likely does.

{m,n} allows m to n (inclusive) occurrences of the previous character.

Examples:

/a{0,3}/ matches 0 to 3 occurrences of a.

/a{3,}/ matches 3 or more occurrences.

/a{3}/ matches exactly 3 occurrences.

In the following example I've paired the above syntax with negative lookahead and negative lookbehind.

(?<!a)a{0,3}(?!a) matches 0 to 3 occurrences of a where there is no a before or after those 0-3 occurrences.