首页 > 为何正则匹配捕获不了“\”反斜杠?

为何正则匹配捕获不了“\”反斜杠?

var str = "\abc";// 字符串是获取到的,不能更改为了\\abc
var re = /^\abc/;
console.log(re.test(str));//true
console.log(str.match(re));
//["abc", index: 0, input: "abc"] 没有'\'
console.log(re.exec(str));
//["abc", index: 0, input: "abc"] 没有'\'


var re2 = /^\\abc/;
console.log(re2.test(str));//false
console.log(str.match(re2));//null
console.log(re2.exec(str));//null

var re3 = /^\\\abc/;
console.log(re3.test(str));//false
console.log(str.match(re3));//null
console.log(re3.exec(str));//null

var re4 = /^\\\\abc/;
console.log(re4.test(str));//false
console.log(str.match(re4));//null
console.log(re4.exec(str));//null

反斜杠“\”是转义字符,如果它出现在字符的前面,那么他们就是一个整体,比如说"n",就表示换行符。
要想验证这个我上面说的,你可以试试下面这行代码:

var str = "\abc";
console.info(str.length); // 3

结果是3,说明'\a'是一个字符。
如果你想在字符串里面表示'\',那么你就得转义它,给它也加一个反斜杠'\\'。
所以你上面的代码应该这么写:

var str = "\\abc";
var re = /^\\abc/;
console.log(re.test(str));//true
console.log(str.match(re));// ["\abc", index: 0, input: "\abc"]

比如var str="hh",会直接解析为hh。如果改成var str="\hh"的话,就是'hh'了。
接下来

var str="\\hh";
/\.*/.test(str) //true

字符串 '\\a' 是转义操作,但是a不是有效的转义符,所以就直接是字符a了。
'\a' === 'a' 是 true
你要这样写 '\\abc' 才是真正的 \abc 字符串。


var a = '\abc' // 打印结果是:abc而不是 \abc

在字符串里匹配\要用\\匹配,比如:

var a = '\\abc'
a.match(/\\/) // 打印结果是:["\"]
【热门文章】
【热门文章】