Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regular expression to extract string

Tags:

python

regex

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?

like image 558
shantanuo Avatar asked Jan 30 '26 07:01

shantanuo


1 Answers

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'
like image 175
mgilson Avatar answered Feb 01 '26 21:02

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!