05 RegExp

 RegExp類型
 g-全局(global)模式,即模式將被應用於所有字符串,而非在發現第一個匹配時立即停止。
 i-表示不區分大小寫模式
 m-多行模式,到達一行文本末尾時還會繼續查找下一行中是否存在與模式匹配的項。

 var pattern = /at/g;  匹配所有"at"的實例
 var pattern = /[bc]at/i;   匹配一個bat或者cat,不區分大小寫
 var pattern =  /.at/gi;       匹配所有以at結尾長度爲三的字符組合,不區分大小寫
var pattern = /\[bc\]at/i     匹配第一個[bc]at,不區分大小寫
var pattern = /\.at/gi        匹配所有.at,不區分大小寫

RegExp實例屬性:
global:是否設置了g標誌
ignoreCase:是否設置了i標誌
lastIndex:整數,表示開始搜索下一個匹配項的字符位置,從0開始
multiline:是否設置了m標誌
source:表示按字符串


Example 1:
var text = "mom and dad and baby";
var pattern =/mon( and dad( and baby)?)?/gi;
var matches = pattern.exec(text); 
alert(matches.index);//0
alert(matches.input);// mom and dad and baby
alert(matches[0]);// mom and dad and baby
alert(matches[1]);// and dad and baby
alert(matches[2]);// and baby


Example 2:
var text ="cat, bat, sat, fat";
var pattern =/.at/; 
var matches = pattern.exec(text);
alert(matches.index);//0
alert(matches[0]);//cat
alert(matches.lastIndex);// 0 
var matches = pattern.exec(text);
alert(matches.index);//0
alert(matches[0]);//cat
alert(matches.lastIndex);// 0


Example 3:
var text ="cat, bat, sat, fat";
var pattern =/.at/G; 
var matches = pattern.exec(text);
alert(matches.index);//0
alert(matches[0]);//cat
alert(matches.lastIndex);// 0 
var matches = pattern.exec(text);
alert(matches.index);//5
alert(matches[0]);//bat
alert(matches.lastIndex);// 0

發佈了1 篇原創文章 · 獲贊 1 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章