【问题标题】:REGEX-String and escaped quote [duplicate]正则表达式字符串和转义引号 [重复]
【发布时间】:2013-04-21 21:28:46
【问题描述】:

如何得到以下两段文字中引号之间的内容?

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

【问题讨论】:

  • 抱歉,我已经编辑了我的问题,因为谷歌翻译添加了一些虚假空格。
  • 你需要更多的转义。为什么要在中间串联?这只会分散你的问题
  • 我也忘记了转义引号,已经完成了。
  • @MartijnPieters 你说得对。现在这是我的 uqestion 的更简单版本。
  • 有什么可忽略的?我没有看到任何逃脱

标签: python regex


【解决方案1】:
"(?:\\.|[^"\\])*"

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

说明:

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

【讨论】:

  • 这给了我unexpected end of regular expression 错误。任何想法为什么?
  • @SaheelGodhane:很可能是因为字符串处理。在 Python 中,如果你想编译这个正则表达式,你需要一个带单引号的原始字符串:re.compile(r'"(?:\\.|[^"\\])*"').
【解决方案2】:
>>> import re
>>> text = "Some text on\n\"two\"lines" + "Another texton\n\"three\"\nlines"
>>> re.findall(r'"(.*)"', text)
["two", "three"]

【讨论】:

  • 对不起,我忘记了我的问题中的一些转义引号。这已更新。
  • 没关系,据我所知。编辑:嗯,确实如此。让我看看。
  • .* 将消耗包括"在内的所有符号,因此如果不是换行\n,它将输出"two\"linesAnother texton\"three\"
  • @projetmbc 很高兴听到这个消息,perreal 仍然给了你正确的答案。如果它符合您的需要,请务必接受它!
  • @Pit Inded 如果使用"..." + "..." 之类的东西,就会出现问题。
【解决方案3】:

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

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

输出

['two', 'three']

【讨论】:

    【解决方案4】:
    >>> 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 字符串以突出显示它们和其他内容。
    • @projetmbc 没关系,你可以提供一个不适用的例子吗?
    • 我已经添加了我想要获取的组。
    • @projetmbc 哦,有道理
    • @projetmbc 好吧,有人明白这一点很好!
    猜你喜欢
    • 2013-02-09
    • 2011-05-03
    • 2012-02-03
    • 2011-10-13
    • 1970-01-01
    • 2010-09-19
    • 2011-06-23
    • 2011-09-25
    • 2010-09-21
    相关资源
    最近更新 更多