5.4 RegExp 類型
實例
g全局 i不區分大小寫 m多行正則表達式
var pattern1 = /[bc]at/i var pattern2 = new RegExp("[bc]at", "i");
5.4.1 RegExp 實例屬性(global,ignoreCase, lastIndex, multiline, source)
global: 布爾,是否設置了g
ignoreCase 布爾,是否設置了i
lastIndex 整數,匹配的字符位置
multiline 布爾,是否設置了m
source 字符串標識,按照字面量形式返回函數
var pattern1 = /\[bc\]at/i l(pattern1.global);//false l(pattern1.ignoreCase);//true l(pattern1.multiline);//false l(pattern1.lastIndex);//0 l(pattern1.source);//\[bc\]at var pattern1 = new RegExp('\\[bc\\]at', 'i') l(pattern1.global);//false l(pattern1.ignoreCase);//true l(pattern1.multiline);//false l(pattern1.lastIndex);//0 l(pattern1.source);//\[bc\]at
5.4.2 RegExp 實例方法(exec(), test())
exec: 接受一個參數,返回應用模式的字符串 index:位置 input:正則表達式字符串
test: 接受一個字符串,匹配返回true,不匹配返回falsethis
var text = 'mom and dad and baby'; var pattern = /mom( and dad( and baby)?)?/gi; var matches = pattern.exec(text); l(matches); l(matches.index);//0 l(matches.input);//mom and dad and baby l(matches[0]);//mom and dad and baby l(matches[1]);// and dad and baby l(matches[2]);// and baby var text = "cat,bat,sat,fat"; var pattern1 = /.at/; var matches = pattern1.exec(text); l(matches.index);//0 l(matches[0]);//cat l(pattern1.lastIndex);//0 matches = pattern1.exec(text); l(matches.index);//0 l(matches[0]);//cat l(pattern1.lastIndex);//0 var pattern2 = /.at/g; matches = pattern2.exec(text); l(matches.index);//0 l(matches[0]);//cat l(pattern2.lastIndex);//3 matches = pattern2.exec(text); l(matches.index);//4 l(matches[0]);//cat l(pattern2.lastIndex);//7
var text = "000-00-0000"; var pattern = /\d{3}-\d{2}-\d{4}/; if(pattern.test(text)){ l('matches');//matches } var pattern = new RegExp("\\[bc\\]at", "gi"); alert(pattern.toString());///\[bc\]at/gi alert(pattern.toLocaleString());///\[bc\]at/gi
5.4.3 RegExp 構造函數屬性(input,lastMatch,lastParen,leftContext,multiline,rightContext)
input($_):最近一次要匹配的字符串
lastMatch($&): 最近一次匹配項
lastParen($+): 最近一次匹配的捕獲組
leftContext($`): input字符串中的lastMatch之前的文本
multiline($*): 布爾值,表示是否因此表達式都使用多行模式
rightContext($') input字符串中的lastMatch以後的文本spa
var text = "this has been a short summer"; var pattern = /(.)hort/g; if(pattern.test(text)){ l(RegExp.input);//this has been a short summer l(RegExp.leftContext);//this has been a l(RegExp.rightContext);// summer l(RegExp.lastMatch);//short l(RegExp.lastParen);//s l(RegExp.multiline);//false }
$1,$2,$3code
var text = "this has been a short summer"; var pattern = /(..)or(.)/g; if(pattern.test(text)){ l(RegExp.$1);//sh l(RegExp.$2);//t }