早期练习正则与字符串的一些记录

时间:2022-01-10 22:26:55
//执行exec方法会将匹配到的坐标记录下来,也就是lastIndex属性
//例如:
var reg = /^#(\w+)$/;
reg.exec("#aNodeId");
alert(reg.lastIndex); //IE下为8 其他浏览器下为0
reg = /^#(\w+)$/g;
reg.exec("#aNodeId");
alert(reg.lastIndex); //IE下为8 其他浏览器下也为8

//抓取匹配项,按照“()”分组抓取
//例如:
var reg = /^#(\w+)$/;
//首先要有一个完全匹配串
var match = reg.exec("#aNodeId");
alert(match.length); //2
alert(match[0]); //#aNodeId
alert(match[1]); //aNodeId

//无全局匹配项 因为没有已#开头
match = reg.exec("aNodeId");
alert(match); //null

//匹配多组(分组由外而内,故第三组匹配项为“23”)
reg = /^(\d+)([\.](\d{1,2}))?$/;
match = reg.exec("9999.23");
alert(match[0]); //9999.23
alert(match[1]); //9999
alert(match[2]); //.23
alert(match[3]); //23

match = reg.exec("9999");
alert(match.index); //0 捕获位置
alert(match.input); //9999 捕获串
alert(match[0]); //9999
alert(match[1]); //9999
alert(match[2]); //"无匹配项,故为空字符串"
alert(match[3]); //"无匹配项,故为空字符串"
alert(match[4]); //undefined 无第四分组
alert(match.length); //4 (完全匹配项和三分组)

//去除重复字符串
reg = /(.+)\1/g;
alert("aabbcddeff".replace(reg,"$1")); //abcdef
alert("aaabbbcddeeeff".replace(reg,"$1")); //aabbcdeef

//字符去3重
reg = /(.+)\1+/g;
alert("aabbcddeff".replace(reg,"$1")); //abcdef
alert("aaabbbcddeeeff".replace(reg,"$1")); //abcdef

reg = /^#([a-z]+)|(\d+)/g;//函数的最后两个参数分别为reg.index(匹配位置)和reg.input(字符串)
"#abc123".replace(reg,function(){
alert("调用函数"); //弹出两次
alert(arguments[0]); //第一次调用“#abc”,第二次调用“123”匹配项
alert(arguments[1])); //第一次调用“abc”,第二次调用“”(空字符串) 捕获组一
alert(arguments[2])); //第一次调用“”(空字符串) ,第二次调用"123" 捕获组二
alert(arguments[3])); //第一次调用“0” ,第二次调用"4" (reg.index)
alert(arguments[4]));//都是“#abc123”(reg.input)
});