表达式括号的作用
提供了分组,分组可以在javascript中、正则中引用。
分组和分支结构
//分组结构 /(ab)+/g //多选分支结构 (p1|p2)
捕获分组
练习: 提取年月日
var regex = /(\d{4})-(\d{2})-(\d{2})/; var string = "2017-06-12"; regex.test(string); // 正则操作即可,例如 //regex.exec(string); //string.match(regex); console.log(RegExp.$1); // "2017" console.log(RegExp.$2); // "06" console.log(RegExp.$3); // "12"
练习: 替换
var regex = /(\d{4})-(\d{2})-(\d{2})/; var string = "2017-06-12"; var result = string.replace(regex, "$2/$3/$1"); console.log(result); // "06/12/2017" 或者: var result = string.replace(regex, function() { return RegExp.$2 + "/" + RegExp.$3 + "/" + RegExp.$1; }); console.log(result); // "06/12/2017" 或者: var result = string.replace(regex, function(match, year, month, day) { return month + "/" + day + "/" + year; }); console.log(result); // "06/12/2017"
反向引用
匹配如下三种格式,且分隔符一致
2016-06-12
2016/06/12
2016.06.12
括号嵌套:
var regex = /^()\1\2\3\4$/;
var string = "1231231233";
console.log( regex.test(string) ); // true
console.log( RegExp.$1 ); // ?
console.log( RegExp.$2 ); // ?
console.log( RegExp.$3 ); // ?
console.log( RegExp.$4 ); // ?
非捕获分组
捕获分组 伪代码是什么?
相关案例
trim实现
替换开头和结尾空白字符
匹配字符串,提取数据(捕获分组)
转换首字母大小写
捕获分组法
非捕获分组法
驼峰化
捕获分组法(作者的代码首字母大写了,怎么消除?)
非捕获分组法
中划线化(驼峰逆过程)
捕获分组法
非捕获分组法
html转义和反转义
// 将HTML特殊字符转换成等值的实体 function escapeHTML(str) { var escapeChars = { '¢' : 'cent', '£' : 'pound', '¥' : 'yen', '€': 'euro', '©' :'copy', '®' : 'reg', '<' : 'lt', '>' : 'gt', '"' : 'quot', '&' : 'amp', '\'' : '#39' }; return str.replace(new RegExp('[' + Object.keys(escapeChars).join('') +']', 'g'), function(match) { return '&' + escapeChars[match] + ';'; }); } console.log( escapeHTML('<div>Blah blah blah</div>') ); // => <div>Blah blah blah</div>
// 实体字符转换为等值的HTML。 function unescapeHTML(str) { var htmlEntities = { nbsp: ' ', cent: '¢', pound: '£', yen: '¥', euro: '€', copy: '©', reg: '®', lt: '<', gt: '>', quot: '"', amp: '&', apos: '\'' }; return str.replace(/\&([^;]+);/g, function(match, key) { if (key in htmlEntities) { return htmlEntities[key]; } return match; }); } console.log( unescapeHTML('<div>Blah blah blah</div>') ); // => <div>Blah blah blah</div>
匹配成对标签
反引用法
作者提供的不支持嵌套匹配,怎么办?
疑问
console.log( "\7\8\9".split("") ); //[ '\u0007', '8', '9' ] 为什么是这个结果? 8和9不转义了?
实例中的待定选项还未完成。。。。