使用Python Regex查找给定字符串中的所有“ 1(0+)1”模式

在本教程中,我们将编写一个程序,使用正则表达式查找字符串中所有1(0 + 1)的出现。我们在Python中有一个re模块,可以帮助我们使用正则表达式。

让我们看一个示例案例。

Input:
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']

请按照以下步骤编写程序代码。

算法

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 match_object.group() method.

让我们看一下代码。

示例

# 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)}")
print()
# printing the matches from the string using result.group() method
print(result)

输出结果

如果运行上面的代码,您将获得以下输出。

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

结论