[PYTHON] A regular expression that finds N or more consecutive substrings of the same character

A regular expression that finds N or more consecutive substrings of the same character.

import re


def nchars(s, n):
    """Find a substring of the same character n or more consecutive in the string s
    """
    assert n > 0
    reg = re.compile("(.)\\1{%d,}" % (n - 1))  #If you take the comma, you get exactly n
    while True:
        m = reg.search(s)
        if not m:
            break
        yield m.group(0)
        s = s[m.end():]


print(list(nchars('a good uuu ee', 2)))
print(list(nchars('aa Ii Uuu Uu e ooo', 3)))

This is the execution result.

['Good', 'uuu', 'ee']
['Good', 'Uuuuuuu', 'ooo']

Recommended Posts

A regular expression that finds N or more consecutive substrings of the same character
# Function that returns the character code of a string
A python regular expression, or a memo of a match object
Calculate the product of matrices with a character expression?
pandas Fetch the name of a column that contains a specific character
Get the number of searches with a regular expression. SeleniumBasic VBA Python
[Python] Note: A self-made function that finds the area of the normal distribution
The story of Django creating a library that might be a little more useful
A program that searches for the same image
[Ansible] Example of playbook that adds a character string to the first line of the file
[Python] A program that finds the shortest number of steps in a game that crosses clouds
[Ruby] How to replace only a part of the string matched by the regular expression?
A story that reduces the effort of operation / maintenance
[Python] A program that counts the number of valleys
Get the variable name of the variable as a character string.
Make a BOT that shortens the URL of Discord
Generate that shape of the bottom of a PET bottle
A story that analyzed the delivery of Nico Nama.
[Python] A program that compares the positions of kangaroos.
[Python] Programming to find the number of a in a character string that repeats a specified number of times.