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

时间:2015-11-13 13:43:20

标签: python regex regex-lookarounds

我有一个字符串:

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 个答案:

答案 0 :(得分:2)

删除管道|它会很好用: Live Demo

这里是{}

之间的多个字符
(?<=)\{[^\}]*\}(?=)

使用 Live Demo

更新

This做的事情是:

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

答案 1 :(得分: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

修改

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

答案 2 :(得分:1)

如果报价是平衡的,您可以使用lookahead检查前方的不均匀数量。如果您知道,只有一个带引号的子字符串,请检查在"

结束前是否只发生一个$
{[^}]+}(?=[^"]*"[^"]*$)

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

{[^}]+}(?=[^"]*"(?:[^"]*"[^"]*")*[^"]*$)
  • {[^}]+}与支持的内容匹配:文字{后跟[^}]+一个或多个non },直至}
  • 在先行内部的
  • [^"]*"匹配,直到第一个引用
  • (?:[^"]*"[^"]*")*后跟零或更多平衡,前面有任意数量的非引号
  • [^"]*$后跟任意数量的非引号,直到结束

See demo at regex101

答案 3 :(得分: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)]