当前位置: 首页 > 编程笔记 >

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

胡天佑
2023-03-14
本文向大家介绍使用Python Regex查找给定字符串中的所有“ 1(0+)1”模式,包括了使用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']

结论

 类似资料:
  • 本文向大家介绍使用Python Regex查找给定字符串中的所有“ 10 + 1”模式,包括了使用Python Regex查找给定字符串中的所有“ 10 + 1”模式的使用技巧和注意事项,需要的朋友参考一下 我们需要在给定的字符串中找到正则表达式模式10 + 1。为此,我们可以使用python中可用的re模块。这个包有一个叫做find all的方法,它接受正则表达式和我们要搜索的字符串。它为我们提

  • 我正在研究弦和一个问题。问题陈述是“将字符串中的所有数字加一”。我没有得到输入数字129和9923所需的输出。有人能帮忙吗!

  • 我遇到了一个问题语句,要在给定的两个子字符串之间找到所有公共子字符串这样一种方式,在每种情况下都必须打印最长的子字符串。问题声明如下: 编写一个程序来查找两个给定字符串之间的公共子字符串。但不包括包含在较长公共子字符串中的子字符串。 null 在这种情况下,您不必使用字符串实用程序方法,如:contains、indexOf、StringTokenizer、split和replace。 我的算法是这

  • 问题内容: 我有绳子。我想通过更改字符串中的字符顺序来从该字符串生成所有排列。例如,说: 我想要的是这样的清单, 目前,我正在迭代字符串的列表强制转换,随机选择2个字母并将它们换位以形成新的字符串,然后将其添加到设置的l强制转换中。根据字符串的长度,我正在计算可能的排列数量,并继续迭代直到集合大小达到极限。必须有更好的方法来做到这一点。 问题答案: itertools模块具有一个有用的方法,称为p

  • 问题内容: 我正在尝试查找“ |”的所有出现 在一个字符串中。 但我得到一个错误: 问题答案: 功能: 将返回的索引列表中的出现。

  • 我正在看《密码蝙蝠》的练习题,我偶然发现了这个。它说: 给定一个字符串和第二个“word”字符串,如果单词出现在字符串的前面,我们会说它与字符串匹配,除非它的第一个字符不需要完全匹配。在匹配时,返回字符串的前面,或者返回空字符串。因此,对于字符串“hippo”,单词“hi”返回“hi”,而“xip”返回“hip”“。单词的长度至少为1。” 到目前为止,这就是我提出的解决方案。它在大部分情况下都能正