fsociety
fsociety

Reputation: 1027

Regular expression in python to capture between everything between 2 words

Pls consider the following:(this is stored in variable op)

>>> print op
sho run int lo0 | sec mtu
 ip mtu 800
R4#

i need to capture everything starting after "sec mtu" and before "#"

So i tried

str=re.search(r'(\bsec\smtu)(\n.*){2}',op,re.M|re.I)
print str.group(1)

however it generates an error

please suggest an alternative

Upvotes: 0

Views: 92

Answers (4)

depsai
depsai

Reputation: 415

Try this one also it will strictly capture.

(sec\smtu)(?:(?!(\#|\1)).)*\#

This regex will capture exactly want you want.

see the DEMO: http://regex101.com/r/qL0mZ1/1

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174706

You could use multiline modifier also.

>>> re.findall('sec mtu([^#]*)#', op, re.M)[0]
'\n ip mtu 800\nR4'
>>> m = re.findall('sec mtu([^#]*)#', op, re.M)[0]
>>> print m

 ip mtu 800
R4
>>> re.search(r'(?:\bsec\smtu)([^#]*)',op, re.M|re.I).group(1)
'\n ip mtu 800\nR4'

Upvotes: 0

Burhan Khalid
Burhan Khalid

Reputation: 174624

Two options:

>>> s = '''sho run int lo0 | sec mtu
...  ip mtu 800
... R4#'''
>>> re.findall('sec mtu(.*)#', s, re.DOTALL)[0]
'\n ip mtu 800\nR4'
>>> s[s.find('sec mtu')+7:s.find('#')]
'\n ip mtu 800\nR4'

Upvotes: 1

vks
vks

Reputation: 67968

(?<=\bsec\smtu\n)(.*?)(?=#)

Try this.Use re.DOTALL.See demo.

http://regex101.com/r/dZ1vT6/54

Upvotes: 0

Related Questions