Sonu K Mishra Sonu K Mishra - 4 months ago 6x
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"


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).