JavaScript正则表达式模式匹配(3)——贪婪模式和惰性模式
1 var pattern=/[a-z]+/; //这里使用了贪婪模式, 2 var str='abcdefg'; 3 alert(str.replace(pattern,'1')); //所有的字符串变成了1 4 5 var pattern=/[a-z]+?/; //这里使用了惰性模式, 6 var str='abcdefg'; 7 alert(str.replace(pattern,'1')); //只有第一个字符变成了1,后面没有匹配 8 9 var pattern=/[a-z]+?/; //开启全局,并且使用惰性模式, 10 var str='abcdefg'; 11 alert(str.replace(pattern,'1')); //每一个字母替换成了1 12 13 var pattern=/6(.*)6/; //使用了贪婪模式, 14 var str='6google6 6google6 6google6'; //匹配到了google6 6google6 6google 15 document.write(str.replace(pattern,'<strong>$1<strong>')); //结果:<strong>google6 6google6 6google<strong> 16 17 var pattern=/6(.*?)6/; //使用了惰性模式, 18 var str='6google6 6google6 6google6'; 19 document.write(str.replace(pattern,'<strong>$1<strong>')); //结果:<strong>google<strong> 6google6 6google6 20 21 var pattern=/6(.*?)6/g; //使用了惰性模式,开启全局 22 var str='6google6 6google6 6google6'; 23 document.write(str.replace(pattern,'<strong>$1<strong>')); 24 //结果:<strong>google<strong> <strong>google<strong> <strong>google<strong> 25 //结果正确 26 27 var pattern=/6([^6]*)6/g; //另一种惰性,屏蔽了6的匹配,也就是两边的包含字符 28 var str='6google6 6google6 6google6'; 29 document.write(str.replace(pattern,'<strong>$1<strong>'));