Skip to content
Advertisement

How can I find an IP address in a long string with REGEX?

I want to find out how can I extract only the correct IP address from a very long string. The problem is that my code extract the IP address even if a part of it has more than 3 digits (which is incorrect).

I tried to learn more about Python REGEX, but I don’t know exactly how to stop it at maximum 3 consecutive digits after a dot. What I mean is that if an IP is 1.2.3.4 it finds it correctly, which is indeed correct, but if an IP is 1.2.3.4567 it also finds it correctly, which is not correct. I don’t know how to say to it that if a group has more than 3 digits, than that’s not an IP address.

JavaScript

It prints 1.2.3.5344 and also 99.99.99.100, but 1.2.3.5344 is not an IP address because it has more than 3 consecutive digits.

Advertisement

Answer

JavaScript

To make it more interesting I added IP addresses at the beginning and end of your string. I am assuming that the ip address needs to be separated by white space on both sides if not at the beginning or end of the string. So I added to the REGEX at the beginning a non-capturing group (?:s|A) that will match either a white space character or the beginning of the string. I have also added to the end of the REGEX a lookahead assertion (?=s|Z) that will match a single white space character or the end of the line without consuming any characters. The above prints out:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement