使用正则表达式,我想检测开始和结束双大括号之间的文本/字符串,并且它应该检测任何内部大括号以及文本。
例如:
{{detect this {{and this as well}} text}} but text does not ends here so it should {{not detect this}}.
我写了这个正则表达式
\{\{[\s\S]+\}\}
但这会选择整个字符串 FROM{{检测这个.... TO {{检测不到这个}}
注意:我为此使用 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}}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)