1

Let's say I have 3 strings:

str1 = 'Hello my name is Ben and my IP address is 127.1.1.1'
str2 = 'Hello my name is Folks and my IP address is 1.2.3.4.5'
str3 = 'Hello all, ip addresses: 1.2.3.4.5, 127.1.2.1, 127.2.1.2'

I would like to get the following output:

find_ip(str1) #['127.1.1.1']
find_ip(str2) #[]
find_ip(str2) #['127.1.2.1', '127.2.1.2']
  1. Criteria:
    • IM addresses with the following form 'x.x.x.x'
    • Regex should be 1 group.
    • The number of digits doesn't matter (111.111.111.111) is good.

P.S The solution of this StackOverflow post does NOT answer this question.

glhr
  • 3,982
  • 1
  • 13
  • 24
Anthony
  • 782
  • 1
  • 9
  • 20

2 Answers2

3

The following Regex matches IPs from 0.0.0.0 to 255.255.255.255, not preceded or followed by a period or a digit:

(?<![\.\d])(?:[0-9]\.|1\d?\d?\.|2[0-5]?[0-5]?\.){3}(?:[0-9]|1\d?\d?|2[0-5]?[0-5]?)(?![\.\d])

Demo: https://regex101.com/r/UUCywc/3

Edit: to avoid matching IPs with a negative number as the first digit (eg. -127.2.1.2), and to allow IPs like 001.001.001.001, then use:

(?<![-\.\d])(?:0{0,2}?[0-9]\.|1\d?\d?\.|2[0-5]?[0-5]?\.){3}(?:0{0,2}?[0-9]|1\d?\d?|2[0-5]?[0-5]?)(?![\.\d])

Demo: https://regex101.com/r/UUCywc/6

Full Python implementation:

import re

str1 = 'Hello my name is Ben and my IP address is 127.1.1.1'
str2 = 'Hello my name is Folks and my IP address is 1.2.3.4.5'
str3 = 'Hello all, ip addresses: 1.2.3.4.5, 127.1.2.1, 127.2.1.2'

def find_ip(test_str):
    regex = re.compile(r"(?<![-\.\d])(?:0{0,2}?[0-9]\.|1\d?\d?\.|2[0-5]?[0-5]?\.){3}(?:0{0,2}?[0-9]|1\d?\d?|2[0-5]?[0-5]?)(?![\.\d])")
    return regex.findall(test_str)

print(find_ip(str1)) #['127.1.1.1']
print(find_ip(str2)) #[]
print(find_ip(str3)) #['127.1.2.1', '127.2.1.2']
glhr
  • 3,982
  • 1
  • 13
  • 24
0

Please try below regular expression. It will get ip addresses that starts with 127 followed by 3 sets of numbers with dots.

re.findall( r'127+(?:\.[0-9]+){3}', str1 )
re.findall( r'127+(?:\.[0-9]+){3}', str2 )
re.findall( r'127+(?:\.[0-9]+){3}', str3 )

Result:

['127.1.1.1']
[]
['127.1.2.1', '127.2.1.2']
âńōŋŷXmoůŜ
  • 6,942
  • 1
  • 15
  • 28