2013-07-10 85 views
3

所以匹配報價,當你不知道這是否是單人或雙人相當容易:匹配所有的全部行情與正則表達式

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

,將搜索字符串的單個或雙引號,並得到了什麼在中間。但是,這是問題:

它將關閉字符串,如果他們包含其他類型的報價!這裏有兩個例子來說明我的意思:

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

正則表達式'[\'"].*?[\'"]'將匹配一個單引號用雙引號,這顯然是不好的。

那麼什麼樣的正則表達式可以匹配兩種類型的引號,但只有匹配實際的字符串,如果它以相同類型的引號結尾。

的情況下,你困惑

這裏有我想要的輸出:

s ="""this is a "test" and this "won't work right" at all""" 
re.findall(expression,s) 
#prints ['"test"','"won\'t work right"'] 

s ="""something is "test" and this is "an 'inner' string" too""" 
re.findall(expression,s) 
['"test"', '"an \'inner\' string"',"'inner'"] 

回答

4

總結你的第一個字符類中捕獲組,然後引用它的另一面與\1

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

太棒了!然後我可以用列表理解來做出正確的列表 –

+0

等等,在我的實際情況中,它是返回一個空白列表。是否有錯誤...'''''''''''re.findall('\ s +(。+?)=([「\'])(。*?)\ 2',s)'s是一個字符串, name =「content」name2 ='more content''等等 –

+0

沒關係...它只能在前面用'r'...爲什麼是這樣? –