lycan1385
lycan1385

Reputation: 127

Python Regex successfully tested on 3 online testers but not working in code

Hi I'm trying to extract the IP's from the beginning and numbers at the end of the following multi-line string. I've tested it successfully on pythex.org, pyregex.com and regex101.com, but it doesn't work when the script is executed. Output of the regex statements are below.

Multi-line string (extracted from a Cisco router using paramiko to SSH):

sh ip bgp summ | in 192.168.190.
192.168.190.3   4          100     166     169       17    0    0 02:27:11            3
192.168.190.4   4          100     169     171       17    0    0 02:26:33            4
R1#

my regex is as follows (I've also tried using the regex flags in the conventional way, i.e as re.M):

re3=re.findall(r"(?im)^(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b)\s+\b4\b.+\s+(\b\d{1,4}\b)$", string1)

when I run the following code:

print(type(string1))
print(type(re3))
print(len(re3))
print(re3)

Output is as follows:

<class 'str'>
<class 'list'>
0
[]

Am I missing something?

Upvotes: 1

Views: 421

Answers (1)

falsetru
falsetru

Reputation: 369274

The string contains carriage return (\r, CR).

# without CR
>>> re.search('(?m)a$', 'a\n')  # matches
<_sre.SRE_Match object; span=(0, 1), match='a'>

# with CR
>>> re.search('(?m)a$', 'a\r\n')  # does not match
>>> re.search('(?m)a\r$', 'a\r\n')
<_sre.SRE_Match object; span=(0, 2), match='a\r'>

Adjust the regular expression to match the CR; Add \r? just before $ (used \r? to make the CR optional)


re3 = re.findall(r"(?im)^(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b)\s+\b4\b.+\s+(\b\d{1,4}\b)\r?$", string1)
#                                                                                          ^^^

Upvotes: 1

Related Questions