如下代码:
<script type="text/javascript">
str = '<!-- My comment \n test -->'
re = /<!--[.\W]*-->/g
str.match(re) // '<!-- My -- comment \n test -->', '<!---->'
</script>
.号可以匹配字母,但是不可以匹配\n,那为什么我在[]号里面又加了一个匹配选项\W来匹配这个\n,为什么这样匹配为null,<script type="text/javascript">
str = '<!-- My comment \n test -->'
re = /<!--[\w\W]*-->/g
str.match(re) // '<!-- My -- comment \n test -->', '<!---->'
</script>
这样就能成功匹配,我不太懂为什么我第一个写法不可以匹配成功?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
.不能放在[]里吧,放在里面会被当成字符的。匹配所有字符推荐采用的就是[\w\W]或者[\s\S]。因为:
js正则说明