【问题标题】:Matching all Full Quotes with Regex使用正则表达式匹配所有全引号
【发布时间】:2013-07-11 04:55:14
【问题描述】:

所以当你不知道它是单引号还是双引号时匹配引号是相当容易的:

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

【问题讨论】:

    标签: python regex


    【解决方案1】:

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

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

    【讨论】:

    • 太棒了!然后我可以使用列表理解来制作正确的列表
    • 等等,在我的实际情况下,它是返回一个空白列表。有什么问题吗...re.findall('\s+(.+?)=(["\'])(.*?)\2',s) 其中 s 是一个字符串,看起来像 stuff name="content" name2='more content' 等等。
    • 没关系...它只适用于前面的r...这是为什么呢?
    • @RyanSaxe:这绝不是 XML/HTML,是吗?至于您的问题,您必须使用原始字符串(注意字符串文字开头之前的小 r 吗?)。它将反斜杠视为反斜杠,因此r'\n' == '\\n'。没有它,你必须写'\\s+(.+?)=(["\\'])(.*?)\\2
    猜你喜欢
    • 2011-03-08
    • 1970-01-01
    • 2014-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多