问题:如何在Python中找到与正则表达式的所有匹配项?

在我编写的程序中,我使用Python re.search()函数在文本块中查找匹配项并打印结果。但是,一旦找到文本块中的第一个匹配项,程序就会退出。

在找到所有匹配项之前程序不停止的情况下,如何重复执行此操作?是否有单独的功能来执行此操作?

In a program I’m writing I have Python use the re.search() function to find matches in a block of text and print the results. However, the program exits once it finds the first match in the block of text.

How do I do this repeatedly where the program doesn’t stop until ALL matches have been found? Is there a separate function to do this?


回答 0

使用re.findallre.finditer代替。

re.findall(pattern, string) 返回匹配字符串的列表。

re.finditer(pattern, string)返回MatchObject对象上的迭代器。

例:

re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']

[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']

Use re.findall or re.finditer instead.

re.findall(pattern, string) returns a list of matching strings.

re.finditer(pattern, string) returns an iterator over MatchObject objects.

Example:

re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']

[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。