How to specify repetitions Regex in Python?


A regular expression is a series of characters that allows you to discover a string or a set of strings using a search pattern. Regular expressions are sometimes known as RegEx. In Python, the re module is used to work with regular expressions.

We can use repetitions in regular expression to match the string in python. To make repetitions possible in regular expression, we indicate the number of times the character is repeating in {}.

Using search() function

In the following example, we match ‘TTTTPPP’ string which is present in the string ‘TTTTTTPPPPPPPPPPPP’. Here, we have used T{4}P{3} to match the required string.

Example

The following example is a program which shows how to specify repetitions Regex in python using search() fucntion. We begin by importing regular expression module.

import re

Then, we have used search() function which is imported from the re module to get the required string. This re.search() function searches the string/paragraph for a match and returns a match object if there is any match. The group() method is used to return the part of the string that is matched.

import re string = 'TTTTTTPPPPPPPPPPPP' match = re.search(r'T{4}P{3}', string) print (match.group(0))

Output

The following output is obtained on executing the above program.

TTTTPPP

Using findall() function

In the following example, we match ‘AAAAABB’ string which is present in the string ‘AAAAAAAAABBBBB’. Here, we have used A{5}B{2} to match the required string.

Example

The following example is a program which shows how to specify repetitions Regex in python using findall() function. We begin by importing regular expression module.

import re

Then, we have used findall() function which is imported from re module.

import re string = 'AAAAAAAAABBBBB' res = re.findall(r'A{5}B{2}', string) print (res)

The re.findall() function returns a list containing all matches.

Output

The following output is obtained on executing the above program.

['AAAAABB']

Updated on: 08-Nov-2022

906 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements