0

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.

1

2 Answers 2

2

Use re :

import re
result = re.findall("\d+\.\d+\.\d+\.\d+", "Hello I am localhost 127.0.0.1")

Output :

['127.0.0.1']
Sign up to request clarification or add additional context in comments.

8 Comments

how can we do same for the ports?
A port is a fixed 4 digit number, so "\d{4}" would do just fine. And, please mark the answer as accepted if it solved your issue. @AnandVyas
Thanks bro :D checking the code and will reply back.
Please note this will catch many invalid "ip addresses" 1.2.3.4444, 999.999.999.999, etc.
I know, but where do you see 1.2.3.4444 or 999.999.999.999 ? Give me one example and I will edit my answer. @TemporalWolf
|
1

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())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.