Python3正则表达式不匹配

2024-06-01 10:06:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用re.findall匹配字符串,但它与任何内容都不匹配:

>>> str = ''' description TESTE ONE Gi0/0/0\n ip vrf forwarding test\n ip address       xxx.xxx.xxx.xxx\n ip flow monitor fnf input\n ip flow monitor fnf output\n negotiation    auto\n cdp enable\n'''
>>> print(str)
     description TESTE ONE Gi0/0/0
     ip vrf forwarding test
     ip address xxx.xxx.xxx.xxx
     ip flow monitor fnf input
     ip flow monitor fnf output
     negotiation auto
     cdp enable
     >>> desc = re.findall(r'^ description (.*)$', str)
     >>> desc
         []"

在regex101.com中,相同的regex正常工作


Tags: testipredescriptionflowonemonitorxxx
2条回答

如果您试图匹配“描述”后面的整个输入字符串,则ApproachingDarknessFish提供的答案是正确的。但是,您正在执行一个findall,这强烈表明您正在查找^ description (.*)$的多个实例,因此您的意思是锚定^$表示的开始和结束,而不是整个字符串的开始和结束。如果是这种情况,那么您不想使用re.DOTALL标志,而想使用re.M标志:

import re

str = ''' description TESTE ONE Gi0/0/0
 ip vrf forwarding test
 ip address       xxx.xxx.xxx.xxx
 ip flow monitor fnf input 
 ip flow monitor fnf output
 negotiation    auto
 cdp enable
 description another one thrown in for good measure!
'''
print(re.findall(r'^ description (.*)$', str, re.M))

印刷品:

['TESTE ONE Gi0/0/0', 'another one thrown in for good measure!']

这种差异是由点(.)字符的行为引起的。在Python's regex syntax中,.默认情况下不匹配换行符,因此字符串中的换行符会导致(.*)组不匹配

可以通过向方法传递re.DOTALL标志来更改行为或.

re.findall(r'^ description (.*)$', str, re.DOTALL)

相关问题 更多 >