Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: how to extract only first IP address from string (in Python)

Tags:

python

regex

Given the following string (or similar strings, some of which may contain more than one IP address):

from mail2.oknotify2.com (mail2.oknotify2.com. [208.83.243.70]) by mx.google.com with ESMTP id dp5si2596299pdb.170.2015.06.03.14.12.03

I wish to extract the first and only the first IP address, in Python. A first attempt with something like ([0-9]{2,}\.){3}([0-9]{2,}){1} when tried out on nregex.com, looks almost OK, matching the IP address fine, but also matches the other substring which roughly resembles an IP address (170.2015.06.03.14.12.03). When the same pattern is passed to re.compile/re.findall though, the result is:

[(u'243.', u'70'), (u'06.', u'03')]

So clearly the regex is no good. How can I improve it so that it's neater and catches all IPV4 address, and how can I make it such that it only matches the first?

Many thanks.

like image 274
Pyderman Avatar asked Dec 19 '22 03:12

Pyderman


1 Answers

Use re.search with the following pattern:

>>> s = 'from mail2.oknotify2.com (mail2.oknotify2.com. [208.83.243.70]) by mx.google.com with ESMTP id dp5si2596299pdb.170.2015.06.03.14.12.03'
>>> import re
>>> re.search(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', s).group()
'208.83.243.70'
like image 64
Jon Clements Avatar answered Dec 21 '22 23:12

Jon Clements