Sonu K Mishra Sonu K Mishra - 1 year ago 127
Python Question

Regular expression substitution in Python

I have a string

line = "haha (as jfeoiwf) avsrv arv (as qwefo) afneoifew"

From this I want to remove all instances of
using some regular expression. I want the output to look like

line = "haha avsrv arv afneoifew"

I tried:

line = re.sub(r'\(+as .*\)','',line)

But this yields:

line = "haha afneoifew"

Answer Source

To get non-greedy behaviour, you have to use *? instead of *, ie re.sub(r'\(+as .*?\) ','',line). To get the desired string, you also have to add a space, ie re.sub(r'\(+as .*?\) ','',line).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download