Reputation: 119
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
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
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
Reputation: 786261
This regex should work:
^(?:(.)(?!(?:.*?\1){4}))*$
Upvotes: 7
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