【问题标题】:How to write regular expression to get everything within a quote如何编写正则表达式以获取报价中的所有内容
【发布时间】:2012-02-26 16:18:09
【问题描述】:

有谁知道如何在 python 中使用正则表达式来获取引号之间的所有内容?

例如,文本:“这里有一些文本”....文本:“这里有更多文本!”...文本:“还有一些数字 - 2343- 这里也是”

文本长度不同,有些还包含标点和数字。如何编写正则表达式来提取所有信息?

我想在编译器中看到什么:

这里有一些文字 更多文字在这里 还有一些数字——2343——也在这里

【问题讨论】:

    标签: python regex


    【解决方案1】:

    这应该适合你:

    "(.*?)"
    

    * 之后放置? 将限制它尽可能少地匹配,因此它不会占用任何引号。

    >>> r = '"(.*?)"'
    >>> s =  'text: "some text here".... text: "more text in here!"... text:"and some numbers - 2343- here too"'
    >>> import re
    >>> re.findall(r, s)
    ['some text here', 'more text in here!', 'and some numbers - 2343- here too']
    

    【讨论】:

      【解决方案2】:

      尝试"[^"]*",即" 后跟零个或多个不是" 的项目,然后是"。 所以:

      pat = re.compile(r'"[^"]*"').
      

      【讨论】:

      • 我比我更喜欢 Karl 的回答。谢谢,卡尔
      【解决方案3】:

      如果要匹配的引用子字符串不包含转义字符,则 Karl Barker 和 Pierce 的答案都将正确匹配。不过,在这两者中,皮尔斯的表达效率更高:

      reobj = re.compile(r"""
          # Match double quoted substring (no escaped chars).
          "                   # Match opening quote.
          (                   # $1: Quoted substring contents.
            [^"]*             # Zero or more non-".
          )                   # End $1: Quoted substring contents.
          "                   # Match closing quote.
          """, re.VERBOSE)
      

      但如果要匹配的引用子字符串确实包含转义字符(例如“她说:\"Hi\" to me.\n"),那么您将需要一个不同的表达式:

      reobj = re.compile(r"""
          # Match double quoted substring (allow escaped chars).
          "                   # Match opening quote.
          (                   # $1: Quoted substring contents.
            [^"\\]*           # {normal} Zero or more non-", non-\.
            (?:               # Begin {(special normal*)*} construct.
              \\.             # {special} Escaped anything.
              [^"\\]*         # more {normal} Zero or more non-", non-\.
            )*                # End {(special normal*)*} construct.
          )                   # End $1: Quoted substring contents.
          "                   # Match closing quote.
          """, re.DOTALL | re.VERBOSE)
      

      我知道有几个表达式可以解决问题,但上面的一个(取自MRE3)是最有效的。请参阅my answer to a similar question,其中比较了这些不同的、功能相同的表达式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-30
        • 2013-12-26
        • 2011-10-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多