JavaScript正则表达式模式匹配(3)——贪婪模式和惰性模式

 var pattern=/[a-z]+/;    //这里使用了贪婪模式,
var str='abcdefg';
alert(str.replace(pattern,'1')); //所有的字符串变成了1 var pattern=/[a-z]+?/; //这里使用了惰性模式,
var str='abcdefg';
alert(str.replace(pattern,'1')); //只有第一个字符变成了1,后面没有匹配 var pattern=/[a-z]+?/; //开启全局,并且使用惰性模式,
var str='abcdefg';
alert(str.replace(pattern,'1')); //每一个字母替换成了1 var pattern=/6(.*)6/; //使用了贪婪模式,
var str='6google6 6google6 6google6'; //匹配到了google6 6google6 6google
document.write(str.replace(pattern,'<strong>$1<strong>')); //结果:<strong>google6 6google6 6google<strong> var pattern=/6(.*?)6/; //使用了惰性模式,
var str='6google6 6google6 6google6';
document.write(str.replace(pattern,'<strong>$1<strong>')); //结果:<strong>google<strong> 6google6 6google6 var pattern=/6(.*?)6/g; //使用了惰性模式,开启全局
var str='6google6 6google6 6google6';
document.write(str.replace(pattern,'<strong>$1<strong>'));
//结果:<strong>google<strong> <strong>google<strong> <strong>google<strong>
//结果正确 var pattern=/6([^6]*)6/g; //另一种惰性,屏蔽了6的匹配,也就是两边的包含字符
var str='6google6 6google6 6google6';
document.write(str.replace(pattern,'<strong>$1<strong>'));
上一篇:Python科学计算PDF


下一篇:검색엔진의 크롤링과 인덱싱의 차이 (robots.txt 파일과 meta robots 태그의 차이점)