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

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

' \ ' 在字符串中也具有让某些普通字符变得不普通的能力,比如 ' \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"]

以上,没有报错..

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

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

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

转载于:https://www.cnblogs.com/yier0705/p/8119437.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值