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


本教程中,我们将编写一个程序,该程序使用regexes查找字符串中所有出现 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']

结论

如果您对本教程有任何疑问,可以在评论部分中提出来。

更新时间: 23-Oct-2019

184 次观看

开启您的职业生涯

完成课程即可获得认证

开始
广告