Regex, That Matches No more Than n Occurrences

13,781

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.

Share:
13,781
Admin
Author by

Admin

Updated on June 13, 2022

Comments

  • Admin
    Admin almost 2 years

    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.