[1]定義:正則又叫規(guī)則或模式,是一個(gè)強(qiáng)大的字符串匹配工具,在javascript中是一個(gè)對(duì)象
[2]特性:
[2.1]貪婪性,匹配最長(zhǎng)的
[2.2]懶惰性,不設(shè)置/g,則只匹配第1個(gè)
[3]兩種寫法:
[3.1]perl寫法(使用字面量形式): var expression = /pattern/flags;
e.g. var pattern = /a/i;//匹配字符串中所有'a'的實(shí)例
[3.1.1]三個(gè)標(biāo)志flags
[a]g:表示全局模式(global)
[b]i:表示不區(qū)分大小寫(ignoreCase)
[c]m:表示多行模式(multiline)
[3.2]js寫法(使用RegExp構(gòu)造函數(shù)):兩個(gè)參數(shù):要匹配的字符串模式、標(biāo)志字符串(可選)
e.g. var pattern = new RegExp('[bc]at','i');
[注意]RegExp構(gòu)造函數(shù)的兩個(gè)參數(shù)都是字符串
[3.3]構(gòu)造函數(shù)與字面量的區(qū)別
[注意]可以使用字面量形式定義的任何表達(dá)式,都可以使用構(gòu)造函數(shù)來(lái)定義
[3.3.1]字面量寫法不支持變量,只能用構(gòu)造函數(shù)的形式來(lái)寫
[tips]獲取class元素(因?yàn)閏lassname是變量,只能使用構(gòu)造函數(shù)的形式)
function getByClass(obj,classname){ var elements = obj.getElementsByTagName('*'); var result = []; var pattern = new RegExp( '^|//s'+ classname + '//s|$'); for(var i = 0; i < elements.length; i++){ if(pattern.test(elements[i].className)){ result.push(elements[i]); } }}[3.3.2]在ECMAScript3中,正則表達(dá)式字面量始終會(huì)共享同一個(gè)RegExp實(shí)例,而使用構(gòu)造函數(shù)創(chuàng)建的每一個(gè)新RegExp實(shí)例都是一個(gè)新實(shí)例
var re = null, i;for(i = 0; i < 10; i++){ re = /cat/g; re.test('catastrophe');}for(i = 0; i < 10; i++){ re = new RegExp('cat','g'); re.test('catastrophe');} [3.3.3]ECMAScript5中規(guī)定,使用正則表達(dá)式字面量必須像直接調(diào)用RegExp構(gòu)造函數(shù)一樣,每次都創(chuàng)建新的RegExp實(shí)例
[4]語(yǔ)法
[重要事項(xiàng)]正則表達(dá)式中不能出現(xiàn)多余空格
[4.0]元字符(14個(gè)):() [] {} / ^ $ | ? * + .
[注意]元字符必須轉(zhuǎn)義,即用/ 加轉(zhuǎn)義字符,用new RegExp寫的正則必須雙重轉(zhuǎn)義
[4.1]轉(zhuǎn)義字符
[4.1.0].號(hào)代表除了換行符/n之外的任意字符
[4.1.1]/d 數(shù)字 /D 非數(shù)字
[4.1.2]/w 字母、數(shù)字、下劃線 /W 非字母、數(shù)字、下劃線
[注意]漢字不屬于/w
[4.1.3]/s 空格 /S 非空格
[4.1.4]/b 邊界符,/w的左側(cè)或右側(cè)不是/w,則會(huì)出現(xiàn)一個(gè)邊界符 /B非邊界符
[4.1.5]/1 表示和前面相同的一個(gè)字符
[tips]找出重復(fù)項(xiàng)最多的字符和個(gè)數(shù)
var str = 'aaaaabbbbbdddddaaaaaaaffffffffffffffffffgggggcccccce';var pattern = /(/w)/1+/g;var maxLength = 0;var maxValue = '';var result = str.replace(pattern,function(match,match1,pos,originalText){ if(match.length > maxLength){ maxLength = match.length; maxValue = match1; }})console.log(maxLength,maxValue);//18 "f" [4.1.6](/w)(/d)/1/2 :/1代表/w當(dāng)時(shí)所代表的值,/2代表/d當(dāng)時(shí)所代表的值
[注意]正則表達(dá)式中的子項(xiàng)必須是用小括號(hào)括起來(lái)的,并且順序以小括號(hào)的前括號(hào)出現(xiàn)的順序?yàn)闇?zhǔn)
[4.1.7]/t 制表符
[4.1.8]/v 垂直制表符
[4.1.9]/uxxxx 查找以十六進(jìn)制xxxx規(guī)定的Unicode字符
[注意1][/u4e00-/u9fa5]代表中文
[注意2]alert()和console.log()里面的字符是系統(tǒng)轉(zhuǎn)義字符
[a]/r return 回車
[b]/n newline 換行
[c]/t table 制表符
[d]/b backspace 退格
[tips]alert里的換行不能用<br>或<br/>,而應(yīng)該用/n。alert里面相當(dāng)于是系統(tǒng)解析的,而不是瀏覽器
e.g.alert('http://www.baidu.com/n/t你好')
[注意3]由于RegExp構(gòu)造函數(shù)的參數(shù)是字符串,所以某些情況下,需要對(duì)字符進(jìn)行雙重轉(zhuǎn)義。所有元字符必須雙重轉(zhuǎn)義,已經(jīng)轉(zhuǎn)義過(guò)的字符也必須雙重轉(zhuǎn)義
//字面量模式 -> 等價(jià)的字符串// //[bc/]at/ "http://[bc//]at"http:// //.at/ "http://.at"http:// /name//age/ "name///age"http:// //d./d{1,2}/ "http://d.//d{1,2}"http:// //w//hello//123/ "http://w////hello////123" [4.2]量詞
[4.2.1]{n}:匹配n次
[4.2.2]{n,m}:匹配至少n次,最多m次
[4.2.3]{n,}:匹配至少n次
[4.2.4]?:相當(dāng)于{0,1}
[4.2.5]*:相當(dāng)于{0,}
[4.2.6]+:相當(dāng)于{1,}
[4.3]位置符號(hào)
[4.3.1]^起始符號(hào)
[4.3.2]結(jié)束符號(hào)為美元符號(hào)
[4.3.3]?=肯定正向環(huán)視
[4.3.4]?!否定正向環(huán)視
[4.4]控制符號(hào)([]:候選 |:或 ^:非 -:到)
[4.4.1](red|blue|green) 查找任何指定的選項(xiàng)
[4.4.2][abc] 查找方括號(hào)之間的任何字符
[4.4.3][^abc] 查找任何不在方括號(hào)之間的字符
[4.4.4][0-9] 查找任何從0到9的數(shù)字
[4.4.5][a-z] 查找任何從小寫a到小寫z的字符
[4.4.6][A-Z] 查找任何從大寫A到大寫Z的字符
[4.4.7][A-z] 查找任何從大寫A到小寫z的字符
[4.4.8][adgk] 查找給定集合內(nèi)的任何字符
[4.4.9][^adgk] 查找給定集合外的任何字符
[4.5]美元符號(hào)
//$$ $//$& 匹配整個(gè)模式的子字符串(與RegExp.lastMatch的值相同)//$` 匹配子字符串之前的子字符串(與RegExp.leftContext的值相同)//$' 匹配子字符串之后的子字符串(與RegExp.rightContext的值相同)//$n 匹配第n個(gè)捕獲組子字符串,其中n等于0-9。$1表示匹配第一個(gè)捕獲組的子字符串(從第1個(gè)算起)//$nn 匹配第nn個(gè)捕獲組的子字符串,其中nn等于01-99
console.log('cat,bat,sat,fat'.replace(/(.a)(t)/g,'$0'))//$0,$0,$0,$0 console.log('cat,bat,sat,fat'.replace(/(.a)(t)/g,'$1'))//ca,ba,sa,faconsole.log('cat,bat,sat,fat'.replace(/(.a)(t)/g,'$2'))//t,t,t,tconsole.log('cat,bat,sat,fat'.replace(/(.a)(t)/g,'$3'))//$3,$3,$3,$3 console.log('cat,bat,sat,fat'.replace(/(.a)(t)/g,'$$'))//$,$,$,$console.log('cat,bat,sat,fat'.replace(/(.a)(t)/g,'$&'))//cat,bat,sat,fatconsole.log('cat,bat,sat,fat'.replace(/(.a)(t)/g,'$`'))//,cat,,cat,bat,,cat,bat,sat,console.log('cat,bat,sat,fat'.replace(/(.a)(t)/g,"$'"))//,bat,sat,fat,,sat,fat,,fat,[5]實(shí)例屬性:通過(guò)實(shí)例屬性可以獲知一個(gè)正則表達(dá)式的各方面信息,但卻沒(méi)有多大用處,因?yàn)檫@些信息全都包含在模式聲明中
[5.1]global:布爾值,表示是否設(shè)置了g標(biāo)志
[5.2]ignoreCase: 布爾值,表示是否設(shè)置了i標(biāo)志
[5.3]lastIndex: 整數(shù),表示開始搜索下一個(gè)匹配項(xiàng)的字符位置,從0算起
[5.4]multiline: 布爾值,表示是否設(shè)置了標(biāo)志m
[5.5]source: 正則表達(dá)式的字符串表示,按照字面量形式而非傳入構(gòu)造函數(shù)中的字符串模式返回
var pattern = new RegExp('//[bc//]at','i');console.log(pattern.global);//falseconsole.log(pattern.ignoreCase);//true console.log(pattern.multiline);//falseconsole.log(pattern.lastIndex);//0console.log(pattern.source);//'/[bc/]at'[6]構(gòu)造函數(shù)屬性(靜態(tài)屬性):適用于作用域中的所有正則表達(dá)式,并且基于所執(zhí)行的最近一次正則表達(dá)式操作而變化。關(guān)于這些屬性的獨(dú)特之處在于可以通過(guò)兩種方式訪問(wèn)它們,即長(zhǎng)屬性名和短屬性名。短屬性名大都不是有效的ECMAScript標(biāo)識(shí)符,所以必須通過(guò)方括號(hào)語(yǔ)法來(lái)訪問(wèn)它們
[6.1]使用這些屬性,可以從exec()方法或text()方法執(zhí)行的操作中提取出更具體的信息
//長(zhǎng)屬性名 短屬性名 說(shuō)明
//input $_ 最近一次要匹配的字符串
//lastMatch $& 最近一次的匹配項(xiàng)
//lastParen $+ 最近一次匹配的捕獲組
//leftContext $` input字符串中l(wèi)astMatch之前的文本
//multiline $* 布爾值,表示是否所有表達(dá)式都使用多行模式
//rightContext $' input字符串中l(wèi)astMarch之后的文本
[注意1]opera不支持短屬性名
[注意2]opera不支持input/lastMatch/lastParen/multiline
[注意3]IE不支持multiline
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);//' summer' console.log(RegExp.lastMatch);//'short' console.log(RegExp.lastParen);//'s' console.log(RegExp.multiline);//false console.log(RegExp['$_']);//'this has been a short summer' console.log(RegExp['$`']);//'this has been a ' console.log(RegExp["$'"]);//' summer' console.log(RegExp['$&']);//'short' console.log(RegExp['$+']);//'s' console.log(RegExp['$*']);//false }[6.2]還有多達(dá)9個(gè)用于存儲(chǔ)捕獲組的構(gòu)造函數(shù)屬性
//RegExp.$1/RegExp.$2/RegExp.$3……到RegExp.$9分別用于存儲(chǔ)第一、第二……第九個(gè)匹配的捕獲組。在調(diào)用exec()或test()方法時(shí),這些屬性會(huì)被自動(dòng)填充
var text = 'this has been a short summer';var pattern = /(..)or(.)/g; if(pattern.test(text)){ console.log(RegExp.$1);//sh console.log(RegExp.$2);//t}[7]實(shí)例方法:
[7.1]exec():專門為捕獲組而設(shè)計(jì),接受一個(gè)參數(shù),即要應(yīng)用模式的字符串。然后返回包含第一個(gè)匹配項(xiàng)信息的數(shù)組。在沒(méi)有匹配項(xiàng)的情況下返回null。返回的數(shù)組包含兩個(gè)額外的屬性:index和input。index表示匹配項(xiàng)在字符串的位置,input表示應(yīng)用正則表達(dá)式的字符串。在數(shù)組中,第一項(xiàng)是與整個(gè)模式匹配的字符串,其他項(xiàng)是與模式中的捕獲組匹配的字符串,如果模式中沒(méi)有捕獲組,則該數(shù)組只包含一項(xiàng)
var text = 'mom and dad and baby and others';var pattern = /mom( and dad( and baby)?)?/gi;var matches = pattern.exec(text);console.log(pattern,matches);//pattern.lastIndex:20//matches[0]:'mom and dad and baby'//matches[1]:' and dad and baby'//matches[2]:' and baby'//matches.index:0//matches.input:'mom and dad and baby and others'
[注意1]對(duì)于exec()方法而言,即使在模式中設(shè)置了全局標(biāo)志(g),它每次也只會(huì)返回一個(gè)匹配項(xiàng)
[注意2]在不設(shè)置全局標(biāo)志的情況下,在同一個(gè)字符串上多次調(diào)用exec(),將始終返回第一個(gè)匹配項(xiàng)的信息
[注意3]在設(shè)置全局標(biāo)志的情況下,每次調(diào)用exec()都會(huì)在字符串中繼續(xù)查找新匹配項(xiàng)
[注意4]IE8-的js實(shí)現(xiàn)在lastIndex屬性上存在偏差,即使在非全局模式下,lastIndex屬性每次也會(huì)變化
var text = 'cat,bat,sat,fat';var pattern1 = /.at/;var matches = pattern1.exec(text);console.log(pattern1,matches);//pattern1.lastIndex:0//matches[0]:'cat'//matches.index:0//matches.input:'cat,bat,sat,fat'matches = pattern1.exec(text); console.log(pattern1,matches); //pattern1.lastIndex:0//matches[0]:'cat'//matches.index:0//matches.input:'cat,bat,sat,fat'
var text = 'cat,bat,sat,fat';var pattern2 = /.at/g;var matches = pattern2.exec(text);console.log(pattern2,matches); //pattern2.lastIndex:3//matches[0]:'cat'//matches.index:0//matches.input:'cat,bat,sat,fat'matches = pattern2.exec(text);console.log(pattern2,matches); //pattern2.lastIndex:7//matches[0]:'bat'//matches.index:4//matches.input:'cat,bat,sat,fat'
[tips]用exec()方法找出匹配的所有位置和所有值
var string = 'j1h342jg24g234j 3g24j1';var pattern = //d/g;var valueArray = [];//值var indexArray = [];//位置var temp = pattern.exec(string);while(temp != null){ valueArray.push(temp[0]); indexArray.push(temp.index); temp = pattern.exec(string); }console.log(valueArray,indexArray);[7.2]test():接受一個(gè)字符串參數(shù),在模式與該參數(shù)匹配的情況下返回true,否則返回false
[注意]常用于只想知道目標(biāo)字符串與某個(gè)模式是否匹配,但不需要知道其文本內(nèi)容的情況,經(jīng)常用在if語(yǔ)句中
var text = '000-00-000';var pattern = //d{3}-/d{2}-/d{4}/;if(pattern.test(text)){ console.log('The pattern was matched');}[8]模式匹配方法
[8.1]match():只接受一個(gè)參數(shù),正則或字符串,把匹配的內(nèi)容保存到一個(gè)數(shù)組中返回
[注意]加上全局標(biāo)記時(shí),match()方法返回值中沒(méi)有index和input屬性
[a]不加/g
var string = 'cat,bat,sat,fat';var pattern = /.at/;var matches = string.match(pattern);console.log(matches,matches.index,matches.input);//['cat'] 0 'cat,bat,sat,fat'
[b]加/g
var string = 'cat,bat,sat,fat';var pattern = /.at/g;var matches = string.match(pattern);console.log(matches,matches.index,matches.input);//['cat','bat','sat','fat'] undefined undefined
[c]字符串
var string = 'cat,bat,sat,fat';var pattern = 'at';var matches = string.match(pattern);console.log(matches,matches.index,matches.input);//['at'] 1 'cat,bat,sat,fat'
[8.2]search():只接受一個(gè)參數(shù),正則或字符串,返回匹配的內(nèi)容在字符串中首次出現(xiàn)的位置,類似于不能設(shè)置起始位置的indexOf,找不到返回-1
[a]正則(加/g和不加/g效果一樣)
var string = 'cat,bat,sat,fat';var pattern = /.at/;var pos = string.search(pattern);console.log(pos);//0
[b]字符串
var string = 'cat,bat,sat,fat';var pattern = 'at';var pos = string.search(pattern);console.log(pos);//1
[tips]找出匹配的所有位置
function fnAllSearch(str,pattern){ var pos = str.search(pattern); var length = str.match(pattern)[0].length; var index = pos+length; var result = []; var last = index; result.push(pos); while(true){ str = str.substr(index); pos = str.search(pattern); if(pos === -1){ break; } length = str.match(pattern)[0].length; index = pos+length; result.push(last+pos); last += index; }return result;} console.log(fnAllSearch('cat23fbat246565sa3dftf44at',//d+/));//[3,9,17,22] [8.3]replace():接收兩個(gè)參數(shù):第一個(gè)參數(shù)為正則表達(dá)式或字符串(待查找的內(nèi)容)、第二個(gè)參數(shù)為字符串或函數(shù)(替換的內(nèi)容)
[a]字符串替換
var string = 'cat,bat,sat,fat';var result = string.replace('at','ond');console.log(result);//'cond,bat,sat,fat'[b]正則無(wú)/g替換
var string = 'cat,bat,sat,fat';var result = string.replace(/at/,'ond');console.log(result);//'cond,bat,sat,fat'
[c]正則有/g替換
var string = 'cat,bat,sat,fat';var result = string.replace(/at/g,'ond');console.log(result);//'cond,bond,sond,fond'
[d]函數(shù)替換:在只有一個(gè)匹配項(xiàng)(即與模式匹配的字符串的情況下,會(huì)向這個(gè)函數(shù)傳遞3個(gè)參數(shù):模式的匹配項(xiàng)、模式匹配項(xiàng)在字符串中的位置、原始字符串。在正則表達(dá)式定義了多個(gè)捕獲組的情況下,傳遞給函數(shù)的參數(shù)依次是模式的匹配項(xiàng)、第一個(gè)捕獲組的匹配項(xiàng)、第二個(gè)捕獲組的匹配項(xiàng)……第N個(gè)捕獲組的匹配項(xiàng),但最后兩個(gè)參數(shù)仍然分別是模式的匹配項(xiàng)在字符串中的位置和原始字符串,這個(gè)函數(shù)返回一個(gè)字符串。
[tips]防止跨站腳本攻擊xss(css)
function htmlEscape(text){ return text.replace(/[<>"&]/g,function(match,pos,originalText){ switch(match){ case '<': return '<'; case '>': return '>'; case '&': return '&'; case '/"': return '"'; } });}console.log(htmlEscape('<p class=/"greeting/">Hello world!</p>'));//<p class=" greeting">Hello world!</p>console.log(htmlEscape('<p class="greeting">Hello world!</p>'));//同上 [9]繼承的方法:都返回正則表達(dá)式字面量,與創(chuàng)建正則表達(dá)式的方式無(wú)關(guān)。要注意的是toString()和toLocaleString()返回的正則表達(dá)式的字符串表示,而valueOf返回的是正則表達(dá)式對(duì)象本身
[9.1]toString()
[9.2]toLocaleString()
[9.3]valueOf()
var pattern = new RegExp('//[bc//]at','gi');console.log(pattern.toString()); // '//[bc/]at/gi'console.log(pattern.toLocaleString()); // '//[bc/]at/gi'console.log(pattern.valueOf()); // //[bc/]at/gi[10]局限性:下列為ECMAScript正則表達(dá)式不支持的特性
[10.1]匹配字符串開始的結(jié)尾的/A和/Z錨(但支持以^和$來(lái)匹配字符串的開始的結(jié)尾)
[10.2]向后查找(但支持向前查找)
[10.3]并集和交集類
[10.4]原子組
[10.5]Unicode支持(單個(gè)字符除外)
[10.6]命名的捕獲組(但支持編號(hào)的捕獲組)
[10.7]s(single單行)和x(free-spacing無(wú)間隔)匹配模式
[10.8]條件匹配
[10.9]正則表達(dá)式注釋
[11]常見實(shí)例
[11.1]兩種方法找出字符串中所有的數(shù)字
[11.1.1]用傳統(tǒng)字符串操作
var str1 = 'j1h342jg24g234j 3g24j1';var array = [];var temp = '';for(var i = 0; i < str1.length; i++){ var value = parseInt(str1.charAt(i));//如果用number將無(wú)法排除空格 if(!isNaN(value)){ temp += str1.charAt(i); }else{ if(temp != ''){ array.push(temp); temp = ''; } }}if(temp != ''){ array.push(temp); temp = ''; }console.log(array);[11.1.2]用正則表達(dá)式完成
var str1 = 'j1h342jg24g234j 3g24j1';array = str1.match(//d+/g);console.log(array);
[11.2]敏感詞過(guò)濾(replace回調(diào)函數(shù)的應(yīng)用)
var string = 'FLG是邪教';var pattern = /FLG|邪教/g;var result = string.replace(pattern,function($0){ var s = ''; for(var i = 0; i < $0.length; i++){ s+= '*'; } return s;})console.log(result);[11.3]日期格式化
var array = ['2015.7.28','2015-7-28','2015/7/28','2015.7-28','2015-7.28','2015/7---28'];function formatDate(date){ return date.replace(/(/d+)/D+(/d+)/D+(/d+)/,'$1'+'年'+'$2'+'月'+'$3'+'日')}var result = [];for(var i = 0 ; i < array.length; i++){ result.push(formatDate(array[i]));}console.log(result);[11.4]獲取網(wǎng)頁(yè)中的文本內(nèi)容
var str = '<p>refds</p><p>fasdf</p>'var pattern = /<[^<>]+>/g;console.log(str.replace(pattern,''));
[11.5]去除首尾空格的trim()兼容寫法
var string = ' my name is littlematch ';console.log(string.replace(/^/s+|/s+$/,''));
希望以上關(guān)于javascript中正則表達(dá)式的描述,能夠?qū)Υ蠹矣兴鶐椭?/p>
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注