sol
sol

Reputation: 119

Regex to limit the instance count of any character in a string

Can a Regex limit the instance count of any character in a string to, say, 5?

For example: abacaada would fail (or match) because of 5 instances of the character a.

To clarify, I was looking for any character, not just 'a'. I.e. no character can repeat more than x times.

Upvotes: 6

Views: 2535

Answers (4)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89639

you can use this pattern to check a string:

^(?!.*(.)(?:.*\1){4})

pattern details:

^                # start anchor
(?!              # negative lookahead: not followed by
    .*           # zero or more characters
    (.)          # a captured character in group 1
    (?:.*\1){4}  # some character and the captured character repeated 4 times
)

Upvotes: 0

Solomon Rutzky
Solomon Rutzky

Reputation: 48924

This works for me:

(.)(?=(?:.*\1){4})

It is very similar to the accepted answer, but uses a Positive Lookahead. It also matches, rather than excludes, a string if any particular character occurs at least 5 times.

The trick, for both this answer and the accepted answer, for matching "any character" is using the \1 to dynamically make use of whatever was captured by the first capturing group.

Upvotes: 1

anubhava
anubhava

Reputation: 786261

This regex should work:

^(?:(.)(?!(?:.*?\1){4}))*$

Working Demo: http://regex101.com/r/nG2dL4

Exlanation

enter image description here

Upvotes: 7

Ben Roux
Ben Roux

Reputation: 7426

This appears to work on a few of my tests (including your case)

(.*a.*){5}

This of course ignores whitespace. If you want this constrained to specific words, you can wrap the regex in \b's

\b(.*a.*){5}\b

Upvotes: 0

Related Questions