我试图使用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正常工作
如果您试图匹配“描述”后面的整个输入字符串,则ApproachingDarknessFish提供的答案是正确的。但是,您正在执行一个
findall
,这强烈表明您正在查找^ description (.*)$
的多个实例,因此您的意思是锚定^
和$
表示行的开始和结束,而不是整个字符串的开始和结束。如果是这种情况,那么您不想使用re.DOTALL
标志,而想使用re.M
标志:印刷品:
这种差异是由点(
.
)字符的行为引起的。在Python's regex syntax中,.
默认情况下不匹配换行符,因此字符串中的换行符会导致(.*)
组不匹配可以通过向方法传递
re.DOTALL
标志来更改行为或.
:相关问题 更多 >
编程相关推荐