Sonu K Mishra Sonu K Mishra - 6 months ago 23
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
"(as...)"
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

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