Reputation: 103
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.
Upvotes: 0
Views: 45
Reputation: 8564
Use re
:
import re
result = re.findall("\d+\.\d+\.\d+\.\d+", "Hello I am localhost 127.0.0.1")
Output :
['127.0.0.1']
Upvotes: 2
Reputation: 1857
Here'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())
Upvotes: 1