【发布时间】:2025-12-18 05:45:01
【问题描述】:
我不明白这种行为。我有这样的例子,需要捕捉html评论。
var str = '.. <!--My -- comment test--> ';
var regex1 = /<!--[.]*-->/g;
var regex2 = /<!--.*-->/g;
alert(str.match(regex1)); // null
alert(str.match(regex2)); // <!--My -- comment test-->
第二个正则表达式regex2 工作正常,准确输出所需内容。第一个显示null。而且我不明白其中的区别。正则表达式<!--[.]*--> 和<!--.*--> 的含义相同-“在<!-- 之后,取除换行符之外的任何字符,数量从0 到尽可能多,并以--> 结尾”。但是对于第二个它有效,而对于第一个则无效。为什么?
UPD。 我已经阅读了 cmets 并且有更新。
var str3 = '.. <!--Mycommenttest--> ';
var str4 = '.. <!--My comment test--> ';
var regex3 = /<!--[\w]*-->/g;
var regex4 = /<!--[\s\S]*-->/g;
alert(str.match(regex3)); // <!--Mycommentstest-->
alert(str.match(regex4)); // <!-- My comment test -->
因此可以使用有限的匹配变量来匹配任何内容。那么应该使用哪种方式正确使用 RegExps 呢?有[] 还是没有它们?无法区分,两者都给出正确的输出。
【问题讨论】:
-
您知道,“贪婪”匹配意味着您的模式将匹配
<!-- Comment --> (Content) <!-- Another Comment -->。我怀疑这不是你想要的。 -
请注意
<!-- foo -- bar -->是an invalid HTML/SGML comment。
标签: javascript regex regex-greedy quantifiers