如下代码:
<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>
这样就能成功匹配,我不太懂为什么我第一个写法不可以匹配成功?
.
不能放在[]
里吧,放在里面会被当成字符的。匹配所有字符推荐采用的就是[\w\W]
或者[\s\S]
。
因为:
. 只能匹配除换行符之外的任意字符 //偏偏里面有一个\n新行符;所以不能匹配。
\W 就能匹配初了数字字母下划线等之外的字符,包括了换行符或者\r\n;所以就能匹配到了!
js正则说明