regex for repeating characters in a string in Python
python-2.7, regex
Solution
I do not understand the regex --> r'(\w*)(\w)\2(\w*)' and r'\1\2\3' It would be helpful if the above regex's are interpreted in an understandable way.
OK, let’s go:
`(\w*)` is any kind of word character (letters, digits, underscore – varies depending on locale settings, can f.e. include french letters with accents), zero or multiple times (by using the quantifier `*`).
Next it tries to match just one single word character `(\w)` – and then that same character again, using `\2`, which is a back reference to the second match in the expression, which was the `\w` character matched before.
And after that, again zero or multiple word characters, same as at the beginning.
If that expression matches, then `self.repl = r'\1\2\3'` replaces it – again, using back references – with the matches that were made capturing subpatterns using parentheses in the search pattern.
So every matched part gets replaced by itself – except for the repeated character match `\2`, which does not have grouping parentheses.
So, if you want to have the repeated char occur at least three times, you modify that part of the expression to `(\w)(\2{2,})'` – `{2,}` is another quantifier saying “match only if the preceding pattern occurs at least two times”. (Only at least two times, since the first character is matched by the preceding `(\w)` already.)
I did not get it to work using the leading and trailing `(\w*)` though – but since these also match zero word characters, I think they can be ditched altogether.
So this should do what you want to achieve:
self.repeat_regexp = re.compile(r'(\w)(\1{2,})')
self.repl = r'\1'
(Since I removed the leading capturing subpattern here, `\2` was replaced by `\1`, referencing the now first capturing subpattern.)
Problem
I am new to Regex. I have a regex which removes repeating characters from a string. ``` >>> self.repeat_regexp = re.compile(r'(\w*)(\w)\2(\w*)') >>> self.repl = r'\1\2\3' ``` The above 2 lines of code strips the repeating characters. For example, `loooooooove` goes to `love`. But I want to change the regex pattern, such that it replaces only if the repeating characters repeat more than 3 times. Expected output: ``` cannot ---> cannot loooooooove ----> love ``` I do not understand the regex `r'(\w*)(\w)\2(\w*)'` and `r'\1\2\3'` It would be helpful if the above regexs are interpreted in an understandable way.