Javascript子字符串多行替换为RegExp
在多行字符串中匹配正则表达式时遇到一些问题Javascript子字符串多行替换为RegExp,javascript,regex,Javascript,Regex,在多行字符串中匹配正则表达式时遇到一些问题 <script> var str="Welcome to Google!\n"; str = str + "We are proud to announce that Microsoft has \n"; str = str + "one of the worst Web Developers sites in the world."; document.write(str.replace(/.*(microsoft).*/gmi, "$
<script>
var str="Welcome to Google!\n";
str = str + "We are proud to announce that Microsoft has \n";
str = str + "one of the worst Web Developers sites in the world.";
document.write(str.replace(/.*(microsoft).*/gmi, "$1"));
</script>
也就是说,replace()方法逐行执行,如果该行中没有匹配项,它只返回整行即使有“m”(多行)修饰符,..多行选项也只会更改代码
^
和$
的工作方式,而不会更改代码
的工作方式
使用一种模式,在该模式中,您可以使用诸如[\w\w]
之类的集合来匹配任何字符,而不是
,因为该模式仅匹配非换行字符
document.write(str.replace(/[\w\W]*(microsoft)[\w\W]*/gmi, "$1"));
document.write(str.replace(/[\w\W]*(microsoft)[\w\W]*/gmi, "$1"));