Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find all the patterns of "1(0+)1" in a given string using Python Regex
In this tutorial, we will find all occurrences of the pattern "1(0+)1" in a string using Python's regex module. The re module provides powerful pattern matching capabilities for text processing.
The pattern "1(0+)1" represents a literal string containing the number 1, followed by parentheses with "0+" inside, and ending with another 1.
Example Input and Output
Input: string = "Sample 1(0+)1 string with 1(0+)1 unnecessary patterns 1(0+)1" Output: Total number of pattern matches are 3 ['1(0+)1', '1(0+)1', '1(0+)1']
Algorithm
Follow these steps to find the pattern:
1. Import the re module 2. Initialize the input string 3. Create a regex pattern using re.compile() with proper escaping 4. Use findall() method to get all matches 5. Display the count and matched patterns
Implementation
import re
# Initialize the string
string = "Sample 1(0+)1 string with 1(0+)1 unnecessary patterns 1(0+)1"
# Create regex pattern - escape special characters
regex = re.compile(r"1\(0\+\)1")
# Find all matching patterns
result = regex.findall(string)
# Print results
print(f"Total number of pattern matches are {len(result)}")
print(result)
Total number of pattern matches are 3 ['1(0+)1', '1(0+)1', '1(0+)1']
Understanding the Regex Pattern
The regex pattern r"1\(0\+\)1" breaks down as follows:
1 - Matches literal character '1'
\( - Matches literal '(' (escaped)
0 - Matches literal character '0'
\+ - Matches literal '+' (escaped)
\) - Matches literal ')' (escaped)
1 - Matches literal character '1'
Alternative Approach Using re.findall() Directly
import re
string = "Sample 1(0+)1 string with 1(0+)1 unnecessary patterns 1(0+)1"
# Direct approach without compiling
matches = re.findall(r"1\(0\+\)1", string)
print(f"Found {len(matches)} matches:")
for i, match in enumerate(matches, 1):
print(f"Match {i}: {match}")
Found 3 matches: Match 1: 1(0+)1 Match 2: 1(0+)1 Match 3: 1(0+)1
Key Points
Remember to escape special regex characters like (, ), and + when searching for literal text. Use raw strings (r"") to avoid double escaping in Python.
Conclusion
Using Python's re module, you can easily find literal patterns by properly escaping special characters. The findall() method returns all non-overlapping matches as a list.
