正则表达式-字符串和转义引号

8
如何获取以下两个文本中引号中的内容?
text_1 = r""" "Some text on \"two\" lines with a backslash escaped\\" \
     + "Another text on \"three\" lines" """

text_2 = r""" "Some text on \"two\" lines with a backslash escaped\\" + "Another text on \"three\" lines" """

对我来说问题在于如果引号被转义,它们应该被忽略,但是有可能反斜杠也被转义。

我想要获得以下分组。

[
    r'Some text on \"two\" lines with a backslash escaped\\',
    r'Another text on \"three\" lines'
]

抱歉,我编辑了我的问题,因为谷歌翻译添加了一些错误的空格。 - user1054158
你需要更多的转义符。为什么要在中间进行连接?那只会分散你的问题的注意力。 - Martijn Pieters
@MartijnPieters 你是对的。这是我问题的简化版本。 - user1054158
有什么需要忽略的吗?我没有看到任何转义。 - jamylak
抱歉,这里有一个更好的例子。 - user1054158
显示剩余5条评论
4个回答

27
"(?:\\.|[^"\\])*"

匹配带引号的字符串,包括其中出现的任何转义字符。

说明:

"       # Match a quote.
(?:     # Either match...
 \\.    # an escaped character
|       # or
 [^"\\] # any character except quote or backslash.
)*      # Repeat any number of times.
"       # Match another quote.

这给了我一个“正则表达式意外结束”的错误。有什么想法为什么会出现这种情况? - Saheel Godhane
1
@SaheelGodhane:很可能是由于字符串处理。在Python中,如果您想编译此正则表达式,则需要使用单引号中的原始字符串:re.compile(r'"(?:\\.|[^"\\])*"') - Tim Pietzcker

1

匹配除双引号外的所有内容:

import re
text = "Some text on \"two\" lines" + "Another text on \"three\" lines"
print re.findall(r'"([^"]*)"', text)

输出

['two', 'three']

1
>>> import re
>>> text = "Some text on\n\"two\"lines" + "Another texton\n\"three\"\nlines"
>>> re.findall(r'"(.*)"', text)
["two", "three"]

抱歉,我在我的问题中忘记了一些转义引号。已经更新。 - user1054158
没关系,就我所知道的来看。编辑:好吧,确实有关系。让我调查一下。 - Pit
3
.*将匹配包括双引号在内的所有符号,所以如果没有换行符\n,它将输出"two\"linesAnother texton\"three\" - ovgolovin
@projetmbc 很高兴听到这个消息,不过 perreal 给出了正确的答案。如果它符合您的需求,请务必接受它! - Pit
@Pit 如果使用类似于“...”+“...”这样的东西,确实会出现问题。 - user1054158

0
>>> import re
>>> text_1 = r""" "Some text on \"two\" lines with a backslash escaped\\" \
     + "Another text on \"three\" lines" """
>>> text_2 = r""" "Some text on \"two\" lines with a backslash escaped\\" + "Another text on \"three\" lines" """
>>> re.findall(r'\\"([^"]+)\\"', text_2)
['two', 'three']
>>> re.findall(r'\\"([^"]+)\\"', text_1)
['two', 'three']

也许您想要这个:

re.findall(r'\\"((?:(?<!\\)[^"])+)\\"', text)

抱歉我的英语不太好,因为它不是我的母语。所以我想“简单地”捕获Python字符串以进行高亮显示和其他操作。 - user1054158
@projetmbc 没问题,你能提供一个这个方法不适用的例子吗? - jamylak
我已经添加了我想要获取的群组。 - user1054158
@projetmbc 好的,很好有人理解这个! - jamylak
很难用非母语的语言让人理解。抱歉。 - user1054158
@projetmbc 哦,我的意思是我尝试了他的解决方案,但它产生了与您要求的不同的结果。无论如何,现在让我们忘记这件事吧! - jamylak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接