Find all the patterns of “1(0+)1” in a given string using Python Regex

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to write a program which finds all the occurrences of the 1(0+1) in a string using the regexes. We have a re module in Python which helps us to work with the regular expressions.

Let's see one sample case.

string = "Sample 1(0+)1 string with 1(0+)1 unnecessary patterns 1(0+)1" Output:
Total number of pattern maches are 3 ['1(0+)1', '1(0+)1', '1(0+)1']

Follow the below steps to write the code for the program.


1. Import the re module.
2. Initialise a string.
3. Create a regex object using regular expression which matches the pattern using the re.compile(). Remember to pass a raw string to the function instead of the usual string.
4. Now, match all the occurrence of the pattern using regex object from the above step and regex_object.findall() method.
5. The above steps return a match object and print the matched patterns using method.

Let's see the code.


 Live Demo

# importing the re module
import re
# initializing the string
string = "Sample 1(0+)1 string with 1(0+)1 unnecessary patterns 1(0+)1"
# creating a regex object for our patter
regex = re.compile(r"\d\(\d\+\)\d") # this regex object will find all the patter ns which are 1(0+)1
# storing all the matches patterns in a variable using regex.findall() method
result = regex.findall(string) # result is a match object
# printing the frequency of patterns
print(f"Total number of pattern maches are {len(result)}")
# printing the matches from the string using method


If you run the above code, you will get the following output.

Total number of pattern maches are 3
['1(0+)1', '1(0+)1', '1(0+)1']


If you have any doubts regarding the tutorial, mention them in the comment section.

Published on 23-Oct-2019 11:52:30