Matching 3 or more of the same character in python

I am trying to use regular expressions to search for three or more than one character in a string. So, for example: “hi” will not match 'ohhh' will be.

I tried doing things like:

re.compile('(?!.*(.)\1{3,})^[a-zA-Z]*$') re.compile('(\w)\1{5,}') 

but doesn't seem to work.

+7
source share
2 answers

(\w)\1{2,} is the regular expression you are looking for.

In Python, it can be specified as r"(\w)\1{2,}"

+10
source

If you are looking for the same character three times in a row, you can do this:

 (\w)\1\1 

if you want to find the same character three times anywhere on the line, you need to put a dot and an asterisk between the parts of the expression above, for example:

 (\w).*\1.*\1 

.* matches any number of any character, so this expression must match any line that has any character of the word that appears three or more times, with any number of any characters between them.

Hope this helps.

+2
source

All Articles