为何正则匹配捕获不了“\”反斜杠?
高洛峰
高洛峰 2016-11-10 16:30:58
[JavaScript讨论组]
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


高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(3)
三叔

反斜杠“\”是转义字符,如果它出现在字符的前面,那么他们就是一个整体,比如说"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 字符串。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号