JavaScript使用RegExp进行正则匹配的方法
本文实例讲述了JavaScript使用RegExp进行正则匹配的方法。分享给大家供大家参考。具体实现方法如下:
<scripttype="text/javascript">
varmatchedTimes=0;
//Matchonedfollowedbyoneormoreb'sfollowedbyoned
//Remembermatchedb'sandthefollowingd
//Ignorecase
myRe=newRegExp("d(b+)(d)","ig");
//等价于myReg=/d(b+)(d)/ig;
myArray=myRe.exec("ecDBDsdbbdz");//ecdbBdbsdbbdz
console.log("RegularExpressionString:"+myRe.source);
console.log("Isglobal?"+myRe.global);
console.log("Ignorecase?"+myRe.ignoreCase);
console.log("Ismulitiline?"+myRe.multiline);
console.log("------------------------------------------------");
logInfo(myArray,myRe);
myArray=myRe.exec("ecDBDsdbbdz");
logInfo(myArray,myRe);
functionlogInfo(myArray,myRe){
matchedTimes++;
console.log("Thisis"+matchedTimes+"timesmatch");
console.log("OriginalString:"+myArray.input);
console.log("MatchResultArray:["+myArray+"]");
console.log("The0-basedindexofthematchinthestring:"+myArray.index);
console.log("Thelastmatchedcharacters:"+myArray[0]);
console.log("Theparenthesizedsubstringmatches[1]:"+myArray[1]);
console.log("Theparenthesizedsubstringmatches[2]:"+myArray[2]);
console.log("Theindexatwhichtostartthenextmatch:"+myRe.lastIndex);
console.log("-----------------------------------------------");
}
myRe2=/^\w+(\d*)$/ig
console.log("myRe2:"+myRe2.source);
//console.log("myRe2matchesabc1?"+myRe2.test("abc1"));
//加上这行跑跑看结果,因为是global匹配,所以lastIndex会改变,
//所以后面的myRe2.test("abc")当然就是false
console.log("myRe2matchesabc?"+myRe2.test("abc"));
</script>
希望本文所述对大家的javascript程序设计有所帮助。