如果某个子字符串存在于内,如何防止正则表达式匹配?

igo*_*GIS 2 regex substring escaping

HTML注释可以使用内联JavaScript作为不支持JS代码的旧浏览器的特殊块.这些块看起来像这样:

<!--
some js code
//-->
Run Code Online (Sandbox Code Playgroud)

我想在JS代码中区分'true'html注释.我写过这个正则表达式:

/<!--[^//]*?-->/g
Run Code Online (Sandbox Code Playgroud)

所以我想在内部用双斜杠排除匹配,但是正则表达式将//字符集视为//,而不是整个双斜杠//.我能做什么?

Tim*_*ker 5

正如您所指出的,字符类只匹配单个字符,因此您不能在此处使用它们.但是你可以使用负前瞻断言:

/<!--(?:(?!//)[\s\S])*-->/g
Run Code Online (Sandbox Code Playgroud)

(假设这是JavaScript).

说明:

<!--     # Match <!--
(?:      # Try to match...
 (?!//)  #  (asserting that there is no // ahead)
 [\s\S]  #  any character (including newlines)
)*       # ...any number of times.
-->      # Match -->
Run Code Online (Sandbox Code Playgroud)