Python - 使用正则表达式查找多个匹配项并将其打印出来 [英] Python - Using regex to find multiple matches and print them out
本文介绍了Python - 使用正则表达式查找多个匹配项并将其打印出来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要从 HTML 源文件中查找表单的内容,我做了一些搜索并找到了很好的方法来做到这一点,但问题是它只打印出第一个找到的内容,我如何遍历它并输出所有表单内容,而不仅仅是第一个?
I need to find content of forms from HTML source file, I did some searching and found very good method to do that, but the problem is that it prints out only first found, how can I loop through it and output all form contents, not just first one?
line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'
matchObj = re.search('<form>(.*?)</form>', line, re.S)
print matchObj.group(1)
# Output: Form 1
# I need it to output every form content he found, not just first one...
推荐答案
但如果您需要在字符串中查找所有正则表达式匹配项,请使用 findall
函数.
But if you ever need to find all regexp matches in a string, use the findall
function.
import re
line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'
matches = re.findall('<form>(.*?)</form>', line, re.DOTALL)
print(matches)
# Output: ['Form 1', 'Form 2']
这篇关于Python - 使用正则表达式查找多个匹配项并将其打印出来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文