Skip to main content
 首页 » 编程设计

python之用于检测双花括号之间文本的正则表达式

2024年08月28日37emanlee

使用正则表达式,我想检测开始和结束双花括号之间的文本/字符串,它应该检测任何内部花括号以及文本。

例如:

{{detect this {{and this as well}} text}} 但文本并未在此处结束,因此它应该{{not detect this}}。

我写了这个正则表达式

\{\{[\s\S]+\}\} 

但这会选择整个字符串,从 {{detect this.... 到 {{not detect this}}

注意:我正在为此使用 python re

请您参考如下方法:

Pyparsing 允许你定义递归语法,但有一些内置的帮助程序来处理像这样的常见语法。请参阅下面带注释的代码示例:

from pyparsing import nestedExpr, ungroup, originalTextFor 
 
# use nestedExpr to define a default expression with left-right nesting markers 
nestedText = ungroup(nestedExpr('{{','}}')) 
 
sample = """{{detect this {{and this as well}} text}} but text does not ends here so it should {{not detect this}}.""" 
 
# note how reporting the results as a list keeps the nesting of {{ }}'s 
print nestedText.parseString(sample).asList() 
# prints ['detect', 'this', ['and', 'this', 'as', 'well'], 'text'] 
 
# if you just want the string itself, wrap with 'originalTextFor' 
print originalTextFor(nestedText).parseString(sample)[0] 
# prints {{detect this {{and this as well}} text}}