[英]Why regular expression pattern does not match only in Python?
我在 notepad++ 和 python 正则表达式测试网站上测试了该模式,效果很好。 但是在python中它不匹配。 regex.search方法返回 None。
文字:
Û Downloads : 20314 times
Û Language : English
Û Format : srt
Û Total : 1 subtitle file
图案:
^.{1,3}\s+(.*?):\s+(.*?)$
脚本:
with open('file.txt','r',encoding='utf-8') as f:
string = f.read()
print(string)
pattern = r'^.{1,3}\s+(.*?):\s+(.*?)$'
regex = re.compile(pattern)
match = regex.search(string,re.UNICODE|re.M)
print( 'Matching "%s"' % pattern)
print (' ', match.group())
print (' ', match.groupdict())
您需要在re.compile()
函数中应用标志,而不是在 search 中:
>>> regex = re.compile(pattern,re.U|re.M)
>>> regex.search(st)
<_sre.SRE_Match object at 0x7f367951b2d8>
>>> regex.search(st).group()
u'\u251c\xa2 Downloads : 20314 times
如果您在re.search
应用标志,它将返回 None :
>>> regex = re.compile(pattern)
>>> regex.search(st,re.U|re.M).group()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.