复杂模式:
*分组:
var reDogDog=/dogdog/g;---------------var reDogDog=/(dog){2}/g;
*引用:(注意带括号和不带括号)
var sMatch="#123456789";
var reNum=/(#(\d+))/;
reNum.test(sMatch);
alert(RegExp.$1+" "+RegExp.$2);
var sChange="1234 5678";
var reMatch=/(\d{4}) (\d{4})/;//注意中间要加空格
var newStr=sChange.replace(reMatch,"$2 $1");//不是“RegExp.$2 RegExp.$1”
alert(RegExp.$1+" "+RegExp.$2);//注意此行是输出:1234 5678,有种把上面的正则给覆盖的感觉(深入的机制不清楚)
alert(sChange+" "+newStr);
*候选:管道符 |
var s1="red";
var s2="blue";
var reS1S2=/(red|blue)/;
alert(reS1S2.test(s1));
alert(reS1S2.test(s2));
*非捕获性分组
var sToMatch="#123456789";
var reNumbers=/#(?:\d+)/;
reNumbers.test(sToMatch);
alert(RegExp.$1);//输出“ ”,因为该分组是非捕获性的
*前瞻
var sToMatch1="bedroom";
var sToMatch2="bedding";
var reBed=/(bed(?=room))/;
alert(reBed.test(sToMatch1));
alert(RegExp.$1);
alert(reBed.test(sToMatch2));
结果:true bed false
*边界:^行开头 $行结尾 \b单词的边界 \B非单词的边界
var sToMatch="Important word is the last one.";
var reLastWord=/(\w+).$/;
reLastWord.test(sToMatch);
alert(RegExp.$1);
*多行模式(下面的例子觉得有问题,去掉g,结果不是我想的那样)
var sToMatch="First second\nthird fourth\nfifth sixth";
var reLastWordOnLine=/(\w+)$/g;
var arrWords=sToMatch.match(reLastWordOnLine);
alert(arrWords);