python - Matching all Full Quotes with Regex -


so matching quotes when don't know if single or double easy:

>>> s ="""this "test" "testing" today""" >>> re.findall('[\'"].*?[\'"]',s) ['"test"', '"testing"'] 

that search string either single or double quotes , inbetween. here issue:

it close strings if contain other type of quote! here 2 examples illustrate mean:

>>> s ="""this "test" , "won't work right" @ all""" >>> re.findall('[\'"].*?[\'"]',s) ['"test"', '"won\''] >>> s ="""something "test" , "an 'inner' string" too""" >>> re.findall('[\'"].*?[\'"]',s) ['"test"', '"an \'', '\' string"'] 

the regular expression '[\'"].*?[\'"]' match single quote double quote, bad.

so regular expression match both types of quotes, match actual string if ends same kind of quote.

in case you're confused

here desired outputs:

s ="""this "test" , "won't work right" @ all""" re.findall(expression,s) #prints ['"test"','"won\'t work right"']  s ="""something "test" , "an 'inner' string" too""" re.findall(expression,s) ['"test"', '"an \'inner\' string"',"'inner'"] 

wrap first character class in capturing group , refer on other side \1:

>>> re.findall(r'([\'"])(.*?)\1',s) [('"', 'test'), ('"', "won't work right")] 

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -