如何在 Python 中找到与正则表达式的所有匹配项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4697882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I find all matches to a regular expression in Python?
提问by kjakeb
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.
在我正在编写的程序中,我让 Python 使用该re.search()函数在文本块中查找匹配项并打印结果。但是,一旦在文本块中找到第一个匹配项,程序就会退出。
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?
如何在找到所有匹配项之前程序不会停止的情况下重复执行此操作?是否有单独的功能来执行此操作?
采纳答案by Amber
Use re.findallor re.finditerinstead.
使用re.findall或re.finditer代替。
re.findall(pattern, string)returns a list of matching strings.
re.findall(pattern, string)返回匹配字符串的列表。
re.finditer(pattern, string)returns an iterator over MatchObjectobjects.
re.finditer(pattern, string)返回MatchObject对象上的迭代器。
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']

