如何在 Python 中找到与正则表达式的所有匹配项? [英] How can I find all matches to a regular expression in Python?

查看:58
本文介绍了如何在 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?

推荐答案

使用 re.findallre.finditer 代替.

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

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

re.finditer(pattern, string)MatchObject 对象.

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

示例:

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

这篇关于如何在 Python 中找到与正则表达式的所有匹配项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆