Skip to main content
 首页 » 编程设计

python之为什么正则表达式模式只在 Python 中不匹配

2024年10月24日33dudu

我在 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() 函数中应用标志,而不是在搜索中:

>>> 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'