首页 文章

正则表达式在引用的字符串中查找所有花括号

提问于
浏览
2

我有一个字符串:

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}

4 回答

  • 1

    如果报价是 balancer 的,您可以使用lookahead来检查前面的不均匀数量 . 如果你知道,只有一个带引号的子串,检查是否只发生一个 " 直到结束 $

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

    See demo . 但如果可能有任何数量的报价部件检查不均匀的数量,直到结束 .

    {[^}]+}(?=[^"]*"(?:[^"]*"[^"]*")*[^"]*$)
    
    • {[^}]+} 匹配支撑物:文字 { 后跟 [^}]+ 一个或多个non } 直到 }
      在前瞻内部

    • [^"]*" 匹配到第一个引用

    • (?:[^"]*"[^"]*")* 后跟零或更多 balancer ,前面有任何数量的非引号

    • [^"]*$ 后跟任意数量的非报价直到结束

    See demo at regex101

  • 2

    删除管道 | 它会很好用:现场演示

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

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

    随着现场演示


    更新:

    This做的事情:

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

    您可以尝试字边界 \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


    EDIT

    如果你只想 {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}']
    
  • 0

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

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

相关问题