【问题标题】:Regex to find all curly brackets within a quoted string正则表达式查找带引号的字符串中的所有大括号
【发布时间】:2016-02-15 02:47:46
【问题描述】:

我有一个字符串:

test_str = 'This is the string and it "contains {0} a" few {1} sets of curly brackets'

我想在这个例子中找到{0}{1},也就是说,括号本身和它们的内容,如果只是在一个集合中双引号。

我已经开始通过匹配双引号中的部分来解决这个问题:

(?<=").*(?=")

https://regex101.com/r/qO0pO2/1

但我很难仅匹配 {0} 部分

如何扩展此正则表达式以匹配 {0}

【问题讨论】:

  • | 的用途是什么?你想捕捉整个事物,而不是非此即彼。环顾四周寻找什么?此外,鉴于 str.format 的工作原理,Python 和/或其标准库中可能有一些非常有效的代码。
  • @jonrsharpe,我将把它用于另一个目的,即在我的文本编辑器中添加语法定义。我必须首先确保括号在双引号之间。
  • 知道引号之间(而不是引号之外)的唯一方法是匹配所有引用的字符串(带有单引号和双引号),从开始到带有{n}的打开双引号字符串里面。

标签: python regex regex-lookarounds


【解决方案1】:

如果报价是平衡的,您可以使用lookahead 来检查前面的不平衡量。如果您知道只有一个带引号的子字符串,请检查是否只有一个 " 直到结尾 $

{[^}]+}(?=[^"]*"[^"]*$)

See demo。但是,如果可能有任何数量的引用部分,请检查数量是否不均,直到结束。

{[^}]+}(?=[^"]*"(?:[^"]*"[^"]*")*[^"]*$)
  • {[^}]+} 匹配括号中的内容:文字 { 后跟 [^}]+ 一个或多个 non} 直到 }
  • [^"]*" 内的前瞻匹配直到第一个引号
  • (?:[^"]*"[^"]*")* 后跟零个或多个平衡,前面是任意数量的非引号
  • [^"]*$ 后跟任意数量的非引号,直到结束

See demo at regex101

【讨论】:

    【解决方案2】:

    你可以试试单词边界\Blookarounds——即

    >>>test_str="This is the string and it contains {0} a few {1} sets of curly brackets"
    >>>re.findall(r'(?<=\B){.*?}(?=\B)',test_str)
    >>>['{0}', '{1}']
    

    观看直播DEMO

    但是如果你的字符串没有word boundary,那么试试lazy quantifier evaluation

    >>>test_str="This is the string and it contains {0} a few {1} sets of curly brackets"
    >>>re.findall(r'{.*?}',test_str)
    >>>['{0}', '{1}']
    

    观看直播DEMO


    编辑

    如果你只想要{0},那么你必须在大括号之前使用转义字符(\),因为大括号是正则表达式,如下所示。

    >>>test_str="This is the string and it contains {0} a few {1} sets of curly brackets"
    >>>re.findall(r'\{0\}',test_str)
    >>>['{0}']
    

    【讨论】:

      【解决方案3】:

      移除管道| 会很好用:Live Demo

      这里是{}之间的多个字符

      (?<=)\{[^\}]*\}(?=)
      

      Live Demo


      更新:

      This 负责:

      ".*({[^\}]*\}).*"
      

      【讨论】:

      • 只要大括号的内容是单个字符
      • 抱歉更改我的问题 - 请查看我的编辑。
      【解决方案4】:

      一个正则表达式可能很难做到,但两个很容易:

      from re import findall
      
      # First find all quoted strings...
      for quoted in findall(r'"[^"]*"', test_str):
          # ...then find all bracketed expressions
          for match in findall(r'\{[^\}]*\}', quoted):
              print(match)
      

      或作为单行:

      [match for match in findall(r'\{[^\}]*\}', quoted) for quoted in findall(r'"[^"]*"', test_str)]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多