Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression with [ or ( in python

Tags:

python

regex

I need to extract IP address in the form

prosseek.amer.corp.com [10.0.40.147]

or

prosseek.amer.corp.com (10.0.40.147)

with Python. How can I get the IP for either case with Python? I started with something like

site = "prosseek.amer.corp.com"
m = re.search("%s.*[\(\[](\d+\.\d+\.\d+\.\d+)" % site, r)

but it doesn't work.

ADDED

m = re.search("%s.+(\(|\[)(\d+\.\d+\.\d+\.\d+)" % site, r)
m.group(2)
m = re.search(r"%s.*[([](\d+\.\d+\.\d+\.\d+)" % site, r)
m.group(1)

seems to work.

like image 776
prosseek Avatar asked Dec 21 '25 14:12

prosseek


1 Answers

You don't need to escape meta-characters (*, (, ), ., ...) in character groups (except ], unless it is the first character in the character group; [][]+ would match a sequence of square brackets.)

Another tip when it comes to Python is to use r'...'-style strings. With them, backslashes has no special meaning. r'\\' would print \\, since backslash has no special meaning:

m = re.search(r"%s.*[([](\d+\.\d+\.\d+\.\d+)" % site, r)

In the above string it doesn't make any difference though, since \d doesn't mean anything in Python, but when it comes to stuff like \r, \\, etc., it makes lives easier.

like image 141
Blixt Avatar answered Dec 23 '25 05:12

Blixt