javascript正規表現の数量詞、文字列の方法(match、search、replace、split)、貪欲モード、惰性モードのまとめ
2311 ワード
1、正規表現の数量詞
var str = "Google";
var pattern = /Google/;
alert(pattern.test(str))
var str = "Go#gle";
var pattern = /Go.gle/; //.
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