匹配所有完整报价与正则表达式

时间:2013-07-10 20:50:40

标签: python regex

如果您不知道单引号还是双引号,那么匹配引号非常简单:

>>> 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'"]

1 个答案:

答案 0 :(得分:4)

将您的第一个角色类包裹在捕获组中,然后使用\1在另一侧引用它:

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