3

I need to extract the IP address from the following string.

>>> mydns='ec2-54-196-170-182.compute-1.amazonaws.com'

The text to the left of the dot needs to be returned. The following works as expected.

>>> mydns[:18]
'ec2-54-196-170-182'

But it does not work in all cases. For e.g.

mydns='ec2-666-777-888-999.compute-1.amazonaws.com'

>>> mydns[:18]
'ec2-666-777-888-99'

How to I use regular expressions in python?

1
  • Its quite hard to give a straight regex answer since all the parts in the string are quite common... Commented Dec 17, 2013 at 6:07

3 Answers 3

5

No need for regex... Just use str.split

mydns.split('.', 1)[0]

Demo:

>>> mydns='ec2-666-777-888-999.compute-1.amazonaws.com'
>>> mydns.split('.', 1)[0]
'ec2-666-777-888-999'
Sign up to request clarification or add additional context in comments.

Comments

2

If you wanted to use regex for this:

Regex String

ec2-([0-9]{1,3})-([0-9]{1,3})-([0-9]{1,3})-([0-9]{1,3}).*

Alternative (EC2 Agnostic):

.*\b([0-9]{1,3})-([0-9]{1,3})-([0-9]{1,3})-([0-9]{1,3}).*

Replacement String

Regular: \1.\2.\3.\4

Reverse: \4.\3.\2.\1

Python code

import re
subject = 'ec2-54-196-170-182.compute-1.amazonaws.com'
result = re.sub("ec2-([0-9]{1,3})-([0-9]{1,3})-([0-9]{1,3})-([0-9]{1,3}).*", r"\1.\2.\3.\4", subject)

print result

4 Comments

Do you by any chance think that hardcoding the ec2 is a good idea? The user might possibly have hundreds of similar ip's!!!
As far as I'm aware, only EC2 instances have DNS names like that. Everything else is usually specified like aws:region:stuff:morestuff/name/items
However you cannot predict the user has only ec2 instances and by any chance if there were any other instances then the user is in trouble...
If that's the case, .*\b([0-9]{1,3})-([0-9]{1,3})-([0-9]{1,3})-([0-9]{1,3}).* can be used instead. I kinda doubt it though. I edited the main post to include the alternative.
2

This regex will match (^[^.]+:

Regular expression visualization

So Try this:

import re

string = "ec2-54-196-170-182.compute-1.amazonaws.com"
ip = re.findall('^[^.]+',string)[0]
print ip

Output:

ec2-54-196-170-182

Best thing is this will match even if the instance was ec2,ec3 so this regex is actually very much similar to the code of @mgilson

1 Comment

Hmm, do you think that ^[^.]+ would be a simple enough regex to do the job?

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.