javascript 正则表达式数量词,字符串方法(match,search,replace,split),贪婪模式,惰性模式总结

1、正则表达式数量词

        var str = "Google";
	var pattern = /Google/;
	alert(pattern.test(str))

	var str = "Go#gle";
	var pattern = /Go.gle/;  //.匹配除换行符和\n和回车符之外的任何单个字符
	alert(pattern.test(str))
  
	var str = "Goooogle";
	var pattern = /Go*gle/;  //*对前面表达式的匹配出现零次或多次
	alert(pattern.test(str))
	
	var str = "Gogle";
	var pattern = /Go+gle/;  //+对前面表达式的匹配至少出现一次
	alert(pattern.test(str));

	var str = "Gogle";
	var pattern = /Go?gle/; //?对前面表达式匹配零次或者一次
	alert(pattern.test(str));
	
	var str = "Google";
	var pattern = /Go{1,2}/;  //对前面表达式匹配1-2次
	alert(pattern.test(str));
	
	var str = "Google";
	var pattern = /^[a-zA-Z]{1}oogle/;
	alert(pattern.test(str));

2、字符串方法(match,search,replace,split)

        var str = "This is an Apple, That is an Apple";
	var pattern = /Apple/g;
	alert(str.match(pattern)); // 搜索子字符串,开启全局匹配,返回一个数组,或者null
	
	var str = "That is an Apple";
	var pattern = /Apple/;
	alert(str.search(pattern));  //返回第一次匹配的索引位置,如果不匹配返回-1

	var str = "This is an Apple, That is an Apple";
	var pattern = /Apple/;
	alert(str.replace(pattern,"Banana"));
	
	var str = "This is an Apple";
	var pattern = /\s/;
	alert(str.split(pattern));  //拆分为数组

	var str = "javascriptjavascriptjavascript";
	var pattern = /^(javascript){2,3}$/;
	alert(pattern.test(str));    //分组匹配2-3次

	var str = "6baidu6";
	var pattern = /6(.*)6/;
	document.write(str.replace(pattern,"<b>$1</b>"));

	var str = "baidu google";
	var pattern = /(\w*)\s(\w*)/;
	document.write(str.replace(pattern,'$2 $1'));  //$1第一个子表达式相匹配的文本,$2表达第二个子表达式相匹配的文本

3、贪婪模式,惰性模式

        var str = "asdfasdf";      
	var pattern = /[a-z]+/;   //贪婪模式
	alert(str.replace(pattern,"1"));
        //结果: 1

	var str = "asdfasdf";      
	var pattern = /[a-z]+?/;   //惰性模式,在数量词后面加?
	alert(str.replace(pattern,"1"));
	//结果:1sdfasdf 

	var str = "asdfaef";
	var pattern = /[a-z]+/g;   //贪婪模式,开启全局匹配
	alert(str.replace(pattern,"1"));
	//结果: 1
	
	var str = "asdfaef";
	var pattern = /[a-z]+?/g;   //惰性模式,开启全局匹配
	alert(str.replace(pattern,"1"));
	//结果: 1111111


你可能感兴趣的:(javascript 正则表达式数量词,字符串方法(match,search,replace,split),贪婪模式,惰性模式总结)