js中为什么字符串中加了\n匹配就一直失败


这样没结果


 var s = 'hi\nabc454def';
console.log(/h.+(\d+)def/g.exec(s));

这样是有结果的


 var s = 'hiabc454def';
console.log(/h.+(\d+)def/g.exec(s));

JavaScript

tyrion 9 years, 2 months ago

点代表除了换行符以外的字符,\n正好是换行符

5487447 answered 9 years, 2 months ago

. 应该不包含 \ 的,改下你的正则试试,

console.log(/h[.\\]+(\d+)def/g.exec(s));

路人甲西奈 answered 9 years, 2 months ago

试试 console.log(/h.+(\d+)def/g.exec(escape(s)));

槌俅﹎綄媄 answered 9 years, 2 months ago


 var s = 'hi\nabc454def';
console.log(/h[\s\S]+(\d+)def/g.exec(s));//["hi↵abc454def", "4", index: 0, input: "hi↵abc454def"]  
console.log(/h[\w\W]+(\d+)def/g.exec(s));//["hi↵abc454def", "4", index: 0, input: "hi↵abc454def"]

大明湖畔夏雨荷 answered 9 years, 2 months ago

http://stackoverflow.com/a/1981692/2586541


js正则不支持单行模式


 console.log(/h(.|\n)+(\d+)def/g.exec(s));

岩泽麻美. answered 9 years, 2 months ago

Your Answer