-1

Here is an example: '192.168.1.1;192.168.1.2'

My code:

import re
regex = '^((?:(?: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]?)[;]?)+$'
r = re.match(regex, '192.168.1.1;192.168.1.2')
r.groups() # => ('192.168.1.2',)
# My expected result => ('192.168.1.1', '192.168.1.2',)

# re.findall(regex, '192.168.1.1;192.168.1.2') => ['192.168.1.2'] is not what I want......

I use () to capture each IP, but the result only shows one IP. Is my usage wrong?

Thanks for your help.

Chien-Wei Huang
  • 1,773
  • 1
  • 17
  • 27
  • 3
    [How can I find all matches to a regular expression in Python?](http://stackoverflow.com/questions/4697882/how-can-i-find-all-matches-to-a-regular-expression-in-python) and [Python - Using regex to find multiple matches and print them out](http://stackoverflow.com/questions/7724993/python-using-regex-to-find-multiple-matches-and-print-them-out) and [Get all possible matches for regex (in python)?](http://stackoverflow.com/questions/7383818/get-all-possible-matches-for-regex-in-python) – Tushar Dec 21 '15 at 08:21
  • Use [`findall`](http://docs.python.org/library/re.html#re.findall) – Tushar Dec 21 '15 at 08:22
  • 1
    do u want both IPs on different lines? – Rohan Amrute Dec 21 '15 at 08:24
  • @Tushar `findall` doesn't show the two IPs in a list. I think maybe my regex is wrong... – Chien-Wei Huang Dec 21 '15 at 09:11
  • 1
    @stribizhev I think the issue is with the regex, `findall` will not solve the problem. – Tushar Dec 21 '15 at 09:12

1 Answers1

0

Just use re.finditer()

import re
regex = '^((?:(?: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]?)[;]?)+$'
for r in re.finditer(regex, '192.168.1.1;192.168.1.2'):
  print r.group()

You can use this regex also if u want: regex = r'(\d{3}\.\d{3}\.\d\.\d)'

Rohan Amrute
  • 764
  • 1
  • 9
  • 23