Skip to content Skip to sidebar Skip to footer

Regex: How To Extract Only First Ip Address From String (in Python)

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.co

Solution 1:

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'

Solution 2:

The regex you want is r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'. This catches 4 1- to 4-digit numbers separated by dots.

If the IP number always comes before other numbers in the string, you can avoid selecting it by using a non-greedy function such as re.find. In contrast, re.findall will catch both 208.83.243.70 and 015.06.03.14.

Are you OK with using the brackets to single out the IP number? if so, you can change the regex to r'\[(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\]'. It would be safer that way.

Post a Comment for "Regex: How To Extract Only First Ip Address From String (in Python)"