正则表达式 中,如何匹配字符串中的 '\'

' \ ' 作为特别功能的转义字符,在正则表达式有举足轻重的重要

' \ ' 在字符串中也具有让某些普通字符变得不普通的能力,比如 ' \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( reg.exec(str) );    // null

reg = /hello/;
console.log( reg.exec(str) );    // ["he\llo", index: 0, input: "he\llo"]
reg = new RegExp('hello');
console.log( reg.exec(str) );
reg = new RegExp('he\llo');
console.log( reg.exec(str) );    
reg = new RegExp('he\\llo');
console.log( reg.exec(str) );
reg = new RegExp('he\\\llo');
console.log( reg.exec(str) );    // ["hello", index: 0, input: "hello"]

reg = /\h\e\l\l\o/;
console.log( reg.exec(str) );    // ["hello", index: 0, input: "hello"]



str = 'he\\llo';
console.log(str);                // he\llo

reg = /he\\llo/;
console.log( reg.exec(str) );    // ["he\llo", index: 0, input: "he\llo"]
reg = new RegExp('he\\\\llo');
console.log( reg.exec(str) );
reg = new RegExp('he\\\\\llo');
console.log( reg.exec(str) );
reg = new RegExp('he\\\\\\llo');
console.log( reg.exec(str) );
reg = new RegExp('he\\\\\\\llo');
console.log( reg.exec(str) );    // ["he\llo", index: 0, input: "he\llo"]

以上,没有报错..

蜜汁 ' \ ' 啊,自行体会吧.. 

实际操作中,当然是用尽可能少的字符.. 在最简 直接量 表示法的基础上,转义 

虽然对的情况很多种,择优

posted @ 2017-12-26 18:21  弋儿  阅读(14746)  评论(0编辑  收藏  举报