I am trying to match the pattern of an IP address. what I have is [0-999].[0-999].[0-999].[0-999] what test data are: 10.37.255.1 , 1.1.1.10 , and 2.2.3.3.3. Unfortunately it picks up the first 2 data sets as well as the first 4 numbers of the third data. what can I do to exclude the third data set in the return?
You could surround your regex pattern by whitespace lookarounds:
inp = "These are my IP addresses 10.37.255.1 and 1.1.1.10 and this is my serial and ID number 4.1.2, 2.2.3.3.3"
ips = re.findall(r'(?<!\S)\d+(?:\.\d+){3}(?!\S)', inp)
print(ips) # ['10.37.255.1', '1.1.1.10']
Side note: [0-999]
does not match the numbers 1 to 999. Instead, it is identical to [1-9]
, which matches any single number from 1 to 9.