-1

This regular expression works to capture IP addresses. I need one to capture this format:
(1.1.1.1,230.1.1.1)

How do I find a proper RegEx?

I would like to extract (S,G) as:

1.1.1.1 230.1.1.1

(...)
match = re.findall(r'^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$' , line)
(...)
Emma
  • 27,428
  • 11
  • 44
  • 69
Mr Bright
  • 17
  • 3

1 Answers1

0

You already have a pattern for one IP address. Now that you want to find a parenthesized pair of IP addresses, you could just repeat that pattern, putting , in between and \( \). If you want to search multiple lines, you may want to add the multiline flag (?m). To actually capture each address en bloc, you have to enclose it as one more group. This would make:

match = re.findall(r'(?m)^\((((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))'
                         +',(((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))\)$' , line)
for m in match:
    S = m[0]
    G = m[4]
    print S, G

That is of course ugly. We can improve it in a way by factoring out the repeated parts, e. g.:

I = '(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'  # pattern for 1 to 255
IP = '(?:' +I+ '\.){3}' +I                      # pattern for IP address
SG = '(?m)^\((' +IP+ '),(' +IP+ ')\)$'          # pattern for (S,G)
match = re.findall(SG, line);
for S, G in match:
    print S, G

Here I also inserted ?: in groups which don't need to be retrieved, so that only the IP addresses remain in the match.

Armali
  • 18,255
  • 14
  • 57
  • 171