If a user inputs a strings with a IP address. I want to extract only the IP For example:
Hello I am localhost 127.0.0.1
I want to get only ip "127.0.0.1" from the whole string, how can i do it? Thanks.
If a user inputs a strings with a IP address. I want to extract only the IP For example:
Hello I am localhost 127.0.0.1
I want to get only ip "127.0.0.1" from the whole string, how can i do it? Thanks.
Use re :
import re
result = re.findall("\d+\.\d+\.\d+\.\d+", "Hello I am localhost 127.0.0.1")
Output :
['127.0.0.1']
1.2.3.4444, 999.999.999.999, etc.1.2.3.4444 or 999.999.999.999 ? Give me one example and I will edit my answer. @TemporalWolfHere's a regex that matches IPv4 addresses:
(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])
You could use it like this
import re
regex = r"(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])"
print(re.search(regex, "string with an ip like 127.0.0.1 in it").group())