Regex to limit the number of instances of any character in a string

Can Regex limit the number of instances of any character in a string, for example, 5?

For example: abacaada will fail (or match) due to 5 instances of the character a.

To clarify, I was looking for any character, not just "a." That is, no character can be repeated more than x times.

+4
source share
4 answers

This regex should work:

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

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

Exlanation

enter image description here

+4
source

This seems like a few of my tests (including your case)

(.*a.*){5}

, , . , , \b

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

:

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

:

^                # 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
)
0

:

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

, Positive Lookahead. , , - 5 .

, , , " " \1, , .

-1

Source: https://habr.com/ru/post/1530688/


All Articles