Match the same character an exact number of times with regular expressions

python, regex

Solution

How about

(?:^|(?<=(.)))(?!\1)(.)\2{n-1}(?!\2)

This will:

- `(?:^|(?<=(.)))`: Make sure that:

- `^`: Either we are at the beginning of the string

- `(?<=(.))`: Either we are not at the beginning of the string; then, capture the character before the match and save it into `\1`

- `(?!\1)(.)`: Match any character that is not `\1` and save it into `\2`

- `\2{n-1}`: Match `\2` n-1 times

- `(?!\2)`: Make sure `\2` cannot be matched looking forward

(The `n-1` is only symbolic; obviously you want to replace this with the actual value of n-1, not with `8-1` or something).

Important edit: The previous version of the regex (`(.)\1{n-1}(?!\1)`) does not work because it fails to account for character matching `\1` behind the match. The regex above fixes this problem.

Problem

I'm trying to use python `re` to find a set of the same letter or number repeated a specific number of times. `(.)` works just fine for identifying what will be repeated, but I cannot find how to keep it from just repeating different characters. here is what I have: ``` re.search(r'(.){n}', str) ``` so for example it would match `9999` from `99997` if `n = 4`, but not if `n = 3`. thanks

Original source