Regular expression with [or (in python

I need to extract the 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 address for any case with Python? I started with something like

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

but that will not 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.

+3
source share
6 answers

You do not need to avoid meta-characters ( *, (, ), ., ...) in a group of characters (except ], unless it is the first character in the symbol group, [][]+will follow the sequence of square brackets.)

, Python, - r'...' -style. . r'\\' \\, :

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

, \d Python, , \r, \\ .., .

+3

[([]

. .

:

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

, :

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

:

  • site re.escape, ; . , site ; , - .
  • Use \s+instead .+between the site name and IP address so that it accepts only spaces.
+1
source
re.findall("(?:\d{1,3}\.){3}\d{1,3}", site)
+1
source

How about just ignoring the brackets?

site = "prosseek.amer.corp.com"
m = re.search("%s.*(\d+\.\d+\.\d+\.\d+)" % site, r)
0
source
import string    
site='prosseek.amer.corp.com (10.0.40.147)'
''.join([c for c in site if c not in string.ascii_letters+' []()']).strip('.')

For some reason, I like it better than regex

0
source

Source: https://habr.com/ru/post/1762311/


All Articles