Regex 正则表达式Python3--为什么
我已经编写了以下python代码Regex 正则表达式Python3--为什么,regex,python-3.5,Regex,Python 3.5,我已经编写了以下python代码 import re def get_items(): text = ''' <a href="/archive/q-fin">Quantitative Finance</a> <a href="/archive/stat">Statistics</a> <a href="/help/general">General information</a> &
import re
def get_items():
text = '''
<a href="/archive/q-fin">Quantitative Finance</a>
<a href="/archive/stat">Statistics</a>
<a href="/help/general">General information</a>
<a href="/help/support">Support and Governance Model</a>
<a href="/help/find">Find</a>
'''
pattern = re.compile(r'<a href="/archive/(.*?)">(.*?)</a>', re.S)
items = re.match(pattern, text).group(1)
print(items)
get_items()
重新导入
def get_items():
文本='''
'''
pattern=re.compile(r'',re.S)
项目=重新匹配(模式、文本)。组(1)
打印(项目)
获取_项()
但它不起作用,为什么
正则表达式如下所示:
pattern = re.compile(r'<a href="/archive/(.*?)">(.*?)</a>', re.S)
pattern=re.compile(r'',re.S)
您的正则表达式是正确的,但是您使用了错误的调用来迭代machtes。请参阅下面使用pattern.finditer(text)
和match.group(1)
的更正版本
重新导入
def get_items():
文本='''
'''
pattern=re.compile(r'',re.S)
对于pattern.finditer中的匹配(文本):
产量匹配组(1)
对于get_items()中的项:
打印(项目)
您的正则表达式是正确的,但是您使用了错误的调用来迭代machtes。请参阅下面使用pattern.finditer(text)
和match.group(1)
的更正版本
重新导入
def get_items():
文本='''
'''
pattern=re.compile(r'',re.S)
对于pattern.finditer中的匹配(文本):
产量匹配组(1)
对于get_items()中的项:
打印(项目)
您在某个地方出错,re.match可能返回一个NoneType
,因为找不到匹配项。您在某个地方出错,re.match可能返回一个NoneType
,因为找不到匹配项。
import re
def get_items():
text = '''
<a href="/archive/q-fin">Quantitative Finance</a>
<a href="/archive/stat">Statistics</a>
<a href="/help/general">General information</a>
<a href="/help/support">Support and Governance Model</a>
<a href="/help/find">Find</a>
'''
pattern = re.compile(r'<a href="/archive/(.*?)">(.*?)</a>', re.S)
for match in pattern.finditer(text):
yield match.group(1)
for item in get_items():
print(item)