js 正则实例

1.匹配url参数

var re = /([^&=]+)=?([^&]*)/g
while (r = re.exec("aaa1a=aabbbbbbb"))
{
alert(r);
}

2.去重复

var ss = "Is is the cost of of gasoline going up up?.\n";
var re = /\b([a-z]+) \1\b/gim; // 创建正则表达式样式。
while (r = re.exec(ss))
{
alert(r);
}
var rv = ss.replace(re, "$1"); // 用一个单词替代两个单词。
document.write(rv);

3.非捕获组

(?:X) (?=X) (?<=X) (?!X) (?<!X)

var re = /(?:abc){2}/;
var str = "abcabc";
alert(re.test(str));
alert(RegExp.$1);

?=n 量词匹配任何其后紧接指定字符串 n 的字符串。

var str = "Is this all there is";
var patt1 = /is(?= all)/;
document.write(str.match(patt1));

var str = "Is this all there is";
var patt1 = /is(?! all)/gi;
document.write(str.match(patt1));

 

你可能感兴趣的:(js)