Reputation:
I'm parsing an iptables' log file seeking for the source IPs. To do so, I'm using two instances of re.findall
, one for finding "SRC=x.x.x.x" and the other for actually getting the IP.
for line in iptables:
src = re.findall('SRC=\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', line)
ip = re.findall('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', src)
Is there a better way to achieve the same result? That is, just getting the SRC IP.
For what I want to do right now it really doesn't matter, but I'd like to know whether are there better methods of achieving the same for future development.
Upvotes: 2
Views: 59
Reputation: 82899
You should put the IP-part into a group, i.e. inside parentheses. This way, you can search
a match and get the group
inside that match.
>>> line = "SRC=127.0.0.1"
>>> m = re.search(r'SRC=(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})', line)
>>> m.group(0)
'SRC=127.0.0.1'
>>> m.group(1)
'127.0.0.1'
Here, group(0)
is the entire match, group(1)
the part enclosed in the first set of ()
, and so on.
Upvotes: 3