我偶然发现了一个我无法解决的正则表达式问题。我想匹配配置文件的一部分,但只有它包含一个特殊字:
{{START}}
{{CONF1}}blah blah ..{{ENDCONF1}}
{{CONF2}}blah blah ..{{ENDCONF2}}
{{END}}
{{START}}
{{CONF1}}blah blah ..{{ENDCONF1}}
{{CONF2}}blah specialword ..{{ENDCONF2}}
{{END}}
{{START}}
{{CONF1}}blah blah ..{{ENDCONF1}}
{{CONF2}}blah blah ..{{ENDCONF2}}
{{END}}
这里我想匹配包含“specialword”的整个块
{{START}}
{{CONF1}}blah blah ..{{ENDCONF1}}
{{CONF2}}blah specialword ..{{ENDCONF2}}
{{END}}
通过玩一些模式,我实现了直接的对立,看起来“所有不包含spacialword”但不是我想要的对立面:/
{{START}}((?!specialword)[\s\S])*?{{END}}
要明确我想要
{{START}}[\s\S]*?{{END}}
匹配的部分
[\s\S]*?
必须包含匹配整个表达式的“specialword”
答案 0 :(得分:4)
{{START}}(?:(?!{{END}})[\s\S])*specialword(?:(?!{{END}})[\s\S])*{{END}}
<强>解释强>
{{START}} # Match {{START}}
(?: # Match...
(?!{{END}}) # ...as long as we haven't reached {{END}} yet:
[\s\S] # any character
)* # any number of times.
specialword # Match "specialword"
(?: # Match (as before)...
(?!{{END}}) # whatever follows, unless it's {{END}}
[\s\S]
)*
{{END}} # Then finally match {{END}}