【发布时间】:2019-10-03 14:21:01
【问题描述】:
re.findall 返回包含预期字符串和意外字符串的元组列表。
我正在执行函数findtags(text) 以在给定段落text 中查找tags。当我调用re.findall(tags, text) 在文本中查找定义的标签时,它返回一个元组列表。列表中的每个元组都包含我希望它返回的字符串。
函数findtags(text)如下:
import re
def findtags(text):
parms = '(\w+\s*=\s*"[^"]*"\s*)*'
tags = '(<\s*\w+\s*' + parms + '\s*/?>)'
print(re.findall(tags, text))
return re.findall(tags, text)
testtext1 = """
My favorite website in the world is probably
<a href="www.udacity.com">Udacity</a>. If you want
that link to open in a <b>new tab</b> by default, you should
write <a href="www.udacity.com"target="_blank">Udacity</a>
instead!
"""
findtags(testtext1)
预期结果是
['<a href="www.udacity.com">',
'<b>',
'<a href="www.udacity.com"target="_blank">']
实际结果是
[('<a href="www.udacity.com">', 'href="www.udacity.com"'),
('<b>', ''),
('<a href="www.udacity.com"target="_blank">', 'target="_blank"')]
【问题讨论】:
标签: python regex python-3.x