Javascript 正则表达式使匹配不那么贪婪
我有以下字符串:Javascript 正则表达式使匹配不那么贪婪,javascript,regex,Javascript,Regex,我有以下字符串: <h2><!--DEL-->This is the title<!-- /DEL --><!-- ADD--><% title %><!--/ADD--></h2> <!--ADD--> <strong>some emphasised text</strong> <!--/ADD--> <ul> <!--ADD--&g
<h2><!--DEL-->This is the title<!-- /DEL --><!-- ADD--><% title %><!--/ADD--></h2>
<!--ADD-->
<strong>some emphasised text</strong>
<!--/ADD-->
<ul>
<!--ADD--><% for each item in list %> <!--/ADD--> <li><!--DEL-->This is the first item in the list<!--/DEL--><!--ADD--><% item %><!--/ADD--></li><!--ADD--><% end for %><!-- /ADD -->
<!--DEL--><li>This is the second item in the list</li><!--/DEL -->
<!--DEL--><li>This is the <strong>third</strong> item in the list</li><!-- /DEL -->
</ul>
这是标题
一些强调的文本
- 这是列表中的第一项
- 这是列表中的第二项
- 这是列表中的第三项
通过正则表达式,我希望它产生以下结果:
<h2><% title %></h2>
<strong>some emphasised text</strong>
<ul>
<% for each item in list %><li><% item %></li><% end for %>
</ul>
一些强调的文本
我正在使用的正则表达式:
template = template.replace(/<\!--\s*?DEL\s*?-->(.*)<\!--\s*?\/DEL\s*?-->/gm, "");
template = template.replace(/<\!--\s*?ADD\s*?-->(.*)<\!--\s*?\/ADD\s*?-->/gm, "$1");
template=template.replace(/(.*)/gm,”;
模板=模板。替换(/(.*)/gm,“$1”);
但目前它正在生产:
<h2><% title %></h2>
<ul>
<% for each item in list %><!-- /ADD --><li><!-- ADD --><% item %><!-- /ADD --></li><!-- ADD --><% end for %>
</ul>
问题1:当同一条线上有多个匹配时,它似乎不喜欢(似乎将它们视为一个大匹配)
问题2:如何使其跨多行匹配?我知道答案。character不允许换行字符,但我使用了/m修饰符(这似乎不起作用)
任何想法都将不胜感激
谢谢。问题1 您只需将通配符设置为惰性:
template = template.replace(/<\!--\s*?DEL\s*?-->(.*?)<\!--\s*?\/DEL\s*?-->/gm, "");
template = template.replace(/<\!--\s*?ADD\s*?-->(.*?)<\!--\s*?\/ADD\s*?-->/gm, "$1");
template=template.replace(/(.*?)/gm,”);
模板=模板。替换(/(.*)/gm,“$1”);
用于问题2。js中没有DOT_ALL修改器。但是use可以使用构造[\s\s],而不是实际匹配所有符号的点。
因此,最终您将使用regexp
/<\!--\s*?DEL\s*?-->([\s\S]*?)<\!--\s*?\/DEL\s*?-->/gm
/([\s\s]*?)/gm
感谢您的快速回复。该死,我差一点就到了!它现在输出正确,除了它仍然输出一些强调的文本,实际上您不需要m修改器。它只影响文本开头(^)和文本结尾($)符号,但表达式中没有tham。