正则表达式学习(二)
Published:
上一篇文章简单介绍一下正则表达式的一些常见的元字符以及一些特性,这篇文章介绍一下正则表达式在 js 里的一些方法。
在源代码中使用字面正则表达式
// 该正则表达式包含单个的字符类,
// 会匹配一个美元符号、一个双引号、一个单引号、一个换行符、0~9的任意数字、一个正斜杠或者一个反斜杠。
// 这个正则表达式硬编码到源代码中。
var reg = /[$"'\n\d\/\\]/;
在 js 中,创建正则表达式的最好方式是使用字面正则表达式的特殊语法。可以简单把正则表达式放在两个正斜杠之间。
创建正则表达式对象
// 字面正则表达式
var reg = /[$"'\n\d\/\\]/;
// 正则表达式对象
var regStr = '[$"\'\\n\\d\\/\\\\]';
var reg = new RegExp(regStr);
如果有一个正则表达式存在一个字符串变量中,那么可以用 RegExp()
构造函数来编译这个正则表达式。注意在字符串之内的正则表达式并没有使用正斜杠来分隔。这些斜杠是属于 js 为字面的 RegExp 对象使用的记法,而不属于正则表达式的一部分。
检查是否可以在目标字符串中找到匹配
if (/regex pattern/.test(str)) {
// match success
}
else {
// match failed
}
test()
方法,如果改正则表达式会匹配目标字符串的一部分或者全部,那么 regexp.test() 就会返回 true,否则返回 false。
检查正则表达式能否整个匹配目标字符串
if (/^regex pattern$/.test(str)) {
// match success
}
else {
// match failed
}
js 并不包含一个函数可以用来检查一个正则表达式是否能够整体匹配一个字符串。解决方案是 ^
添加到正则表达式开头,$
加到正则表达式结尾,注意不要为正则表达式设置 m
标志。只有在不使用 m
标志的情况下,^
和 $
才能只匹配文本的开头和结尾。如果设置了 m
标志,它们还会匹配字符串中间的换行符。
获取匹配文本
var str = 'This number is 12 and 123';
var result = str.match(/\d+/g);
if (result) {
console.log(result);
}
else {
// match failed
}
string.match()
方法接收一个正则表达式作为参数。这个参数可以使用字面正则表达式、正则表达式对象或者一个字符串。如果参数是字符串,那么此方法会创建一个临时的 regexp 对象。当匹配失败的时候,此方法会返回 null。当匹配成功时,会返回一个包含匹配细节的数组。
获取匹配的位置和长度
var start = -1;
var length = -1;
var str = 'This number is 12 and 123';
var match = /\d+/.exec(str);
if (match) {
start = match.index;
length = match[0].length;
console.log(match, start, length);
}
使用一个 regexp 对象调用 exec()
方法,可以得到一个关于匹配详细信息的数组。这个数组包含几个属性,index 属性保存正则匹配在目标字符串中的开始位置。如果匹配是从字符串的开头开始,那么 index 值为 0。数组中的0号元素保存的是整个正则匹配的一个字符串。使用这个字符串的 length 属性,可以知道匹配的长度。如果正则表达式不能匹配此字符串,则 exec()
方法返回 null。
注意:不要使用 exec()
方法返回数组中的 lastIndex
属性来确定最终匹配的位置。在一个严格的 js 实现中,lastIndex
属性根本不会在返回的数组中出现而只会出现在 regexp 对象中。同样的,也不应该使用 regexp.lastIndex,因为不同浏览器的区别,它也是不可靠的。正确的做法是,把 match.index
与 match[0].length
加起来来确定正则匹配的结束位置。
获取匹配文本的一部分
var str = 'http://tieba.baidu.com/p/2886801533';
var match = /http:\/\/[\w.-]+/.exec(str);
if (match) {
console.log(match[0]);
}
获取所有匹配的列表
var str = 'The number is 12, 13, 14, 15, 16';
var list = str.match(/\d+/g);
console.log(list);
替换所有匹配
var str = 'The str is aaa, bbb, ccc, aaa, ddd';
var result = str.replace(/aaa/g, 'xxx');
console.log(result);
使用匹配的子串来替换匹配
例如,要匹配由等号分隔的单词对,然后把等号两边的单词互换。
var str = 'aaa=bbb';
var result = str.replace(/(\w+)=(\w+)/g, '$2=$1');
console.log(result);
使用代码中生成的替换文本来替换匹配
var str = 'The number is 12, 13, 14, 15, 16';
var result = str.replace(/\d+/g, function (match) {
return match * 2;
});
console.log(result);
替换另一个正则式匹配中的所有匹配
// 把下列字符串中被 <b\> 包围的 before 换为 after
var str = 'before <b>first before</b> before <b>before before</b>';
var reg = /<b>.*?<\/b>/g;
var result = str.replace(reg, function (match) {
return match.replace(/before/g, 'after');
});
拆分字符串
// 使用 html tag 来拆分一个包含 html tag 的字符串,返回一个不包含 html tag 的字符串数组
var str = 'I like <b>bold</b> and <i>italic</i> fonts';
var result = str.split(/<[^<>]*>/);
console.log(result);
// 使用 split 会有一些跨浏览器的问题,因此推荐正则的方式:
var list = [];
var reg = /<[^<>]*>/g;
var match = null;
var lastIndex = 0;
while (match = reg.exec(str)) {
if (match.index === reg.lastIndex) {
reg.lastIndex++;
}
list.push(str.substring(lastIndex, match.index));
lastIndex = match.index + match[0].length;
}
list.push(str.substring(lastIndex));
console.log(list);
逐行查找
// 如果有一个多行字符串,那么首先要把它拆分成一个字符串数组,该数组中的每个字符串都包含一行文本。
var lines = str.split(/\r?\n/);
var reg = /regex pattern/;
for (var i = 0, len = line.length; i < len; i++) {
if (lines[i].match(reg)) {
// match sucess
}
else {
// match failed
}
}