Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

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.

like image 909
sol Avatar asked Mar 07 '14 21:03

sol


People also ask

How do you find multiple occurrences of a string in regex?

Method 1: Regex re. To get all occurrences of a pattern in a given string, you can use the regular expression method re. finditer(pattern, string) . The result is an iterable of match objects—you can retrieve the indices of the match using the match. start() and match.

What is regex for any character?

A regular expression (shortened as regex or regexp; sometimes referred to as rational expression) is a sequence of characters that specifies a search pattern in text. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation.


1 Answers

This regex should work:

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

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

Exlanation

enter image description here

like image 150
anubhava Avatar answered Oct 06 '22 18:10

anubhava