正则表达式中,如何匹配字符串中的
' \ ' 作为特别功能的转义字符,在正则表达式有举⾜轻重的重要
' \ ' 在字符串中也具有让某些普通字符变得不普通的能⼒,⽐如 ' \t ', ' \n ' 这些众所周知的;当 '\’ + 某个字符不具有特殊功能时,加不加其实都没差别,正则中亦是如此
var str = 'he\tllo';
console.log(str);                // he    llo
如何匹配字符串中的 ' \ ' 呢?(单个 '\' 其实是⽆法被匹配的)
 如果⽤直接量表⽰正则,作为⼀个功能字符,想表⽰⾃⼰,当然是需要转义⼀下的
 如果⽤创建 RegExp 对象的⽅法来写时,参数1 最好是字符串。在字符串中,'\' 想表⽰⾃⼰,也需要转义 '\\'
1、确定真实的字符串
2、写正则表达式
举个栗⼦:
str = 'he\llo';
console.log(str);                // hello
var reg = /he\\llo/;
console.log( (str) );    // null
reg = /hello/;
console.log( (str) );    // ["he\llo", index: 0, input: "he\llo"]
reg = new RegExp('hello');
console.log( (str) );
reg = new RegExp('he\llo');
console.log( (str) );
reg = new RegExp('he\\llo');
console.log( (str) );
reg = new RegExp('he\\\llo');
console.log( (str) );    // ["hello", index: 0, input: "hello"]
reg = /\h\e\l\l\o/;
console.log( (str) );    // ["hello", index: 0, input: "hello"]
str = 'he\\llo';
console.log(str);                // he\llo
reg = /he\\llo/;
console.log( (str) );    // ["he\llo", index: 0, input: "he\llo"]
reg = new RegExp('he\\\\llo');
console.log( (str) );
reg = new RegExp('he\\\\\llo');
console.log( (str) );
reg = new RegExp('he\\\\\\llo');
查匹配的字符串函数
console.log( (str) );
reg = new RegExp('he\\\\\\\llo');
console.log( (str) );    // ["he\llo", index: 0, input: "he\llo"]
以上,没有报错..
蜜汁 ' \ ' 啊,⾃⾏体会吧..
实际操作中,当然是⽤尽可能少的字符.. 在最简直接量表⽰法的基础上,转义
虽然对的情况很多种,择优

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。