Anand Vyas
Anand Vyas

Reputation: 103

Parsing number from a group of strings Python

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

Answers (2)

Jarvis
Jarvis

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

user3030010
user3030010

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

Related Questions