Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"

like image 503
Sonu Mishra Avatar asked Dec 19 '22 16:12

Sonu Mishra


1 Answers

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

like image 98
stephan Avatar answered Dec 21 '22 09:12

stephan