标签:
1.正则表达式的创建:
var pattern1 = /at/g;
var pattern2 = /[bc]at/i;
var pattern = new RegExp("[bc]at", "i");
/\[bc\]at/; "\\[bc\\]at";
/\.at/; "/\\.at/";
/name\/age/; "/name\\/age/";
/\d.\d{1,2}/; "\\d.\\d{1,2}";
/\w\\hello\\123/; "\\w\\\\hello\\\\123";
var re = null, i; for(var i = 0; i < 10; i++) { re = /cat/g; console.log(re.test("catastrophe")); } for(var i = 0; i < 10; i++) { re = new RegExp("cat", "g"); console.log(re.test("catastrophe")); }
v
ar pattern1 = /\[bc\]at/i; console.log(pattern1.global);//false console.log(pattern1.ignoreCase);//true console.log(pattern1.multiline);//false console.log(pattern1.lastIndex);//0 console.log(pattern1.source); ///\[bc\]at/i var pattern2 = new RegExp("\\[bc\\]at", "i"); console.log(pattern2.global); console.log(pattern2.ignoreCase); console.log(pattern2.multiline); console.log(pattern2.lastIndex); console.log(pattern2.source);
var pattern = /mom (and dad (and baby)?)?/gi;
var text = "mom and dad and baby"; var pattern = /mom (and dad (and baby)?)?/gi; var matches = pattern.exec(text); console.log(matches.index); //0 console.log(matches.input); //mom and dad and baby console.log(matches[0]); //mom and dad and baby console.log(matches[1]); //and dad and baby console.log(matches[2]); //and baby
var text = "cat, bat, sat, fat"; var pattern1 = /.at/; var matches = pattern1.exec(text); console.log(pattern1.lastIndex); //0 console.log(matches.index); //0 console.log(matches[0]); `//cat matches = pattern1.exec(text); console.log(pattern1.lastIndex); //0 console.log(matches.index); //0 console.log(matches[0]); //cat var pattern2 = /.at/g; matches = pattern2.exec(text); console.log(pattern2.lastIndex); //3 console.log(matches.index); //0 console.log(matches[0]); //cat matches = pattern2.exec(text); console.log(pattern2.lastIndex); //8 console.log(matches.index); //5 console.log(matches[0]); //bat
var text = "000-00-0000"; var pattern = /\d{3}-\d{2}-\d{4}/; if(pattern.test(text)) { console.log("The pattern is matched"); }
var pattern = new RegExp("\\[bc\\]at", "gi"); console.log(pattern.toString()); console.log(pattern.toLocaleString());
var text = "this has been a short summer"; var pattern = /(.)hort/g; if(pattern.test(text)) { console.log(RegExp.input); //this has been a short summer console.log(RegExp.leftContext); //this has been a console.log(RegExp.rightContext);// short summer console.log(RegExp.lastMatch);//short console.log(RegExp.lastParen);//s console.log(RegExp.multiline);//false; }
var text = "this has been a short summer"; var pattern = /(.)hort/g; if(pattern.test(text)) { console.log(RegExp.$_); console.log(RegExp["$`"]); console.log(RegExp["$‘"]); console.log(RegExp["$&"]); console.log(RegExp["$+"]); console.log(RegExp["$*"]); }
var text = "this has a short summer"; var pattern = /(..)or(.)/g; if(pattern.test(text)) { console.log(RegExp.$1); //sh console.log(RegExp.$2); //t console.log(RegExp.$3); //(空字符串) }
标签:
原文地址:http://www.cnblogs.com/yugege/p/4821016.html