I am trying to use re.findall to match a string, but it doesn't match anything:
>>> 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
[]"
In regex101.com, the same regex works normally.
The discrepancy is caused by the behavior of the dot ( .
) character. In Python's regex syntax , .
does not match newlines by default, hence the line breaks in your strings cause the (.*)
group to not match.
The behavior or .
can be changed by passing the re.DOTALL
flag to the method:
re.findall(r'^ description (.*)$', str, re.DOTALL)
The answer provided by ApproachingDarknessFish is correct if you are attempting to match the entire input string that follows ' description ' as provided. However, you are doing a findall
, which strongly suggests that you are looking for multiple occurrences of ^ description (.*)$
and you therefore mean for the anchors ^
and $
to represent the start and end of lines rather than the start and end of the entire string. If that is the case, then you do not want to use the re.DOTALL
flag but rather the re.M
flag:
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))
Prints:
['TESTE ONE Gi0/0/0', 'another one thrown in for good measure!']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.