Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to express this kind of non greedy regular expression in python?

Tags:

python

regex

s1='haha "h1" "hi"'
s2='haha "h1" "hi hi"'

I want to get "hi" from s1 ,and "hi hi" from s2.

>>> re.search('".*"$',s1).group()
'"h1" "hi"'
>>> re.search('".*"$',s2).group()
'"h1" "hi hi"'
>>> re.search('"*?.*"$',s1).group()
'haha "h1" "hi"'
>>> re.search('"*?.*"$',s2).group()
'haha "h1" "hi hi"'
like image 774
showkey Avatar asked Dec 01 '25 03:12

showkey


1 Answers

Just capture everything that is not " between ":

>>> re.search('"[^"]*"$',s1).group()
'"hi"'
>>> re.search('"[^"]*"$',s2).group()
'"hi hi"'
like image 107
fredtantini Avatar answered Dec 03 '25 18:12

fredtantini