博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
正则表达式 中,如何匹配字符串中的 '\'
阅读量:4659 次
发布时间:2019-06-09

本文共 1491 字,大约阅读时间需要 4 分钟。

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

' \ ' 在字符串中也具有让某些普通字符变得不普通的能力,比如 ' \t ', ' \n ' 这些众所周知的;当 '\’ + 某个字符 不具有特殊功能时,加不加其实都没差别,正则中亦是如此

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

 

如何匹配字符串中的 ' \ ' 呢?( 单个 '\' 其实是无法被匹配的 )

 如果用直接量表示正则,作为一个功能字符,想表示自己,当然是需要转义一下的

 如果用创建 RegExp 对象的方法来写时,参数1 最好是字符串。 在字符串中,'\' 想表示自己,也需要转义 '\\' 

1、确定真实的字符串 

2、写正则表达式

举个栗子:

str = 'he\llo';console.log(str);                // hellovar reg = /he\\llo/;console.log( reg.exec(str) );    // nullreg = /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\lloreg = /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

你可能感兴趣的文章
MVC5+EF6 入门完整教程六
查看>>
PHP的Reflection反射机制
查看>>
Java入门的程序汇总
查看>>
D3js初探及数据可视化案例设计实战
查看>>
java.text.MessageFormat
查看>>
1_ROS学习
查看>>
转I/O多路复用之select
查看>>
理解 YOLO
查看>>
检查Linux文件变更Shell脚本
查看>>
ActiveMQ中JMS的可靠性机制
查看>>
oracle操作字符串:拼接、替换、截取、查找
查看>>
”语义“的理解
查看>>
210. Course Schedule II
查看>>
月薪3000与月薪30000的文案区别
查看>>
使用spring dynamic modules的理由
查看>>
Leetcode 117 Populating Next Right Pointers in Each Node 2
查看>>
C++ Primer 第四版中文版
查看>>
变量关系
查看>>
android Service中启动Dialog
查看>>
文件下载之ServletOutputStream
查看>>