【问题标题】:Regex that match if the match contains special word如果匹配包含特殊单词,则匹配的正则表达式
【发布时间】:2013-06-25 11:13:26
【问题描述】:

我偶然发现了一个我无法解决的正则表达式问题。我想匹配配置文件的一部分,但前提是它包含一个特殊的单词:

{{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}}

这里我想匹配包含“特殊词”的整个块

{{START}}
    {{CONF1}}blah blah ..{{ENDCONF1}}
    {{CONF2}}blah specialword ..{{ENDCONF2}}
{{END}}

通过玩弄一些模式,我实现了直接相反的环视“所有不包含空间词”,但不是我想要的相反:/

{{START}}((?!specialword)[\s\S])*?{{END}}

说清楚我想要

{{START}}[\s\S]*?{{END}}

匹配的部分在哪里

[\s\S]*?

必须包含“特殊词”以匹配整个表达式

【问题讨论】:

  • 这是一个 XML 文件吗?如果没有,请坚持使用({{START}}[\s\S]*?specialword[\s\S]*?{{END}})
  • @RubensFarias:这将无法正常工作。在上面的例子中,它将匹配前两组。
  • @RubensFarias:我犯了同样的错误;)

标签: regex


【解决方案1】:

lookahead assertions 的你走在正确的轨道上:

{{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}}

【讨论】:

  • 感谢您的超级解释!我心里有这样的想法,但不知道如何表达。我想我必须更深入地研究那个 (?:) 事情。非常感谢您简短而准确的回答!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-14
  • 2011-10-02
  • 2017-07-05
  • 1970-01-01
  • 2017-02-06
相关资源
最近更新 更多