定義
正則又叫規(guī)則或模式,是一個(gè)強(qiáng)大的字符串匹配工具。javascript通過RegExp類型來支持正則表達(dá)式
特性
[1]貪婪性,匹配最長的
[2]懶惰性,不設(shè)置/g,則只匹配第1個(gè)
寫法
perl寫法(使用字面量形式)
var expression = /pattern/flags;
模式(pattern)部分可以是任何簡單或復(fù)雜的正則表達(dá)式,可以包含字符串、限定類、分組、向前查找以及反向引用。每個(gè)正則表達(dá)式可以帶一個(gè)或多個(gè)標(biāo)志(flags),用以標(biāo)明正則表達(dá)式的行為。正則表達(dá)式支持三個(gè)標(biāo)志:
[1]g:表示全局模式(global)
[2]i:表示不區(qū)分大小寫(ignoreCase)
[3]m:表示多行模式(multiline)
//匹配字符串所有'at'的實(shí)例var pattern1 = /at/g;
RegExp構(gòu)造函數(shù)
RegExp構(gòu)造函數(shù)接收兩個(gè)參數(shù):要匹配的字符串模式(pattern)和標(biāo)志字符串(flags)(可選)
[注意]RegExp構(gòu)造函數(shù)的兩個(gè)參數(shù)都是字符串。且使用字面量形式定義的任何表達(dá)式都可使用構(gòu)造函數(shù)
//匹配字符串所有'at'的實(shí)例var pattern = new RegExp('at','g'); 兩種寫法的區(qū)別
字面量寫法不支持變量,只能用構(gòu)造函數(shù)的形式來寫
[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]); } } return result;} [注意]ES3中,正則表達(dá)式字面量始終共享同一個(gè)RegExp實(shí)例,而使用構(gòu)造函數(shù)創(chuàng)建的每一個(gè)新RegExp實(shí)例都是一個(gè)新實(shí)例。ES5中規(guī)定使用正則字面量必須像直接調(diào)用RegExp構(gòu)造函數(shù)一樣,每次都創(chuàng)建新的RegExp實(shí)例
語法
[注意]正則表達(dá)式中不能出現(xiàn)多余空格
元字符(14個(gè))
() [] {} / ^ $ | ? * + .
[注意]元字符必須轉(zhuǎn)義,即用/ 加轉(zhuǎn)義字符,用new RegExp寫的正則必須雙重轉(zhuǎn)義
轉(zhuǎn)義字符
. 除換行符/n之外的任意字符
/d 數(shù)字
/D 非數(shù)字
/w 字母、數(shù)字、下劃線
/W 非字母、數(shù)字、下劃線(漢字不屬于/w)
/s 空格
/S 非空格
/b 邊界符(/w的左側(cè)或右側(cè)不是/w,則會出現(xiàn)一個(gè)邊界符)
/B 非邊界符
/1 表示和前面相同的一個(gè)字符
/t 制表符
/v 垂直制表符
/uxxxx 查找以十六進(jìn)制xxxx規(guī)定的Unicode字符(/u4e00-/u9fa5代表中文)
(/w)(/d)/1/2 :/1代表/w當(dāng)時(shí)所代表的值,/2代表/d當(dāng)時(shí)所代表的值
[注意]正則表達(dá)式中的子項(xiàng)必須是用小括號括起來的,并且順序以小括號的前括號出現(xiàn)的順序?yàn)闇?zhǔn)
[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" 系統(tǒng)轉(zhuǎn)義
alert()和console.log()里面的字符是系統(tǒng)轉(zhuǎn)義字符
/0 空字節(jié)
/n 換行
/t 制表
/b 空格
/r 回車
/f 進(jìn)紙
// 斜杠
/' 單引號
/" 雙引號
/xnn 以十六進(jìn)制nn表示一個(gè)字符(n為0-f),如/x41表示'A'
/unnnn 以十六進(jìn)制nnnn表示一個(gè)Unicode字符(n為0-f),如/u03a3表示希臘字符ε
[注意]alert里面的換行不能用<br>或<br/>,而應(yīng)該用/n
alert('http://www.baidu.com/n/t你好') 雙重轉(zhuǎn)義
由于RegExp構(gòu)造函數(shù)的參數(shù)是字符串,所以某些情況下,需要對字符進(jìn)行雙重轉(zhuǎn)義。所有元字符必須雙重轉(zhuǎn)義,已經(jīng)轉(zhuǎn)義過的字符也必須雙重轉(zhuǎn)義
字面量模式 -> 等價(jià)的字符串//[bc/]at/ "http://[bc//]at"http://.at/ "http://.at"/name//age/ "name///age"http://d./d{1,2}/ "http://d.//d{1,2}"http://w//hello//123/ "http://w////hello////123" 量詞
{n} 匹配n次
{n,m} 匹配至少n次,最多m次
{n,} 匹配至少n次
? 相當(dāng)于{0,1}
* 相當(dāng)于{0,}
+ 相當(dāng)于{1,}
位置符號
^ 起始符號
$ 結(jié)束符號
?= 肯定正向環(huán)視
?! 否定正向環(huán)視
控制符號
[] 候選
| 或
^ 非
- 到
(red|blue|green) 查找任何指定的選項(xiàng)
[abc] 查找方括號之間的任何字符
[^abc] 查找任何不在方括號之間的字符
[0-9] 查找任何從0到9的數(shù)字
[a-z] 查找任何從小寫a到小寫z的字符
[A-Z] 查找任何從大寫A到大寫Z的字符
[A-z] 查找任何從大寫A到小寫z的字符
[adgk] 查找給定集合內(nèi)的任何字符
[^adgk] 查找給定集合外的任何字符
$符號
$$ $
$& 匹配整個(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, 構(gòu)造函數(shù)屬性
適用于作用域中的所有正則表達(dá)式,并且基于所執(zhí)行的最近一次正則表達(dá)式操作而變化。關(guān)于這些屬性的獨(dú)特之處在于可以通過兩種方式訪問它們,即長屬性名和短屬性名。短屬性名大都不是有效的ECMAScript標(biāo)識符,所以必須通過方括號語法來訪問它們
長屬性名 短屬性名 說明
input $_ 最近一次要匹配的字符串
lastMatch $& 最近一次的匹配項(xiàng)
lastParen $+ 最近一次匹配的捕獲組
leftContext $` input字符串中l(wèi)astMatch之前的文本
multiline $* 布爾值,表示是否所有表達(dá)式都使用多行模式
rightContext $' Input字符串中l(wèi)astMarch之后的文本
使用這些屬性,可以從exec()方法或text()方法執(zhí)行的操作中提取出更具體的信息
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 } //javascript有9個(gè)用于存儲捕獲組的構(gòu)造函數(shù)屬性。RegExp.$1/RegExp.$2/RegExp.$3……到RegExp.$9分別用于存儲第一、第二……第九個(gè)匹配的捕獲組。在調(diào)用exec()或test()方法時(shí),這些屬性會被自動填充
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} 實(shí)例屬性
通過實(shí)例屬性可以獲知一個(gè)正則表達(dá)式的各方面信息,但卻沒多大用處,因?yàn)檫@些信息都包含在模式聲明中
global: 布爾值,表示是否設(shè)置了g標(biāo)志
ignoreCase: 布爾值,表示是否設(shè)置了i標(biāo)志
lastIndex: 整數(shù),表示開始搜索下一個(gè)匹配項(xiàng)的字符位置,從0算起
multiline: 布爾值,表示是否設(shè)置了標(biāo)志m
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' 繼承的方法
共toString()、toLocaleString()和valueOf()三個(gè)方法,且都返回正則表達(dá)式字面量,與創(chuàng)建正則表達(dá)式的方式無關(guān)。要注意的是toString()和toLocaleString()返回的正則表達(dá)式的字符串表示,而valueOf返回的是正則表達(dá)式對象本身
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 實(shí)例方法
exec()
專門為捕獲組而設(shè)計(jì),接受一個(gè)參數(shù),即要應(yīng)用模式的字符串。然后返回包含第一個(gè)匹配項(xiàng)信息的數(shù)組。在沒有匹配項(xiàng)的情況下返回null。返回的數(shù)組包含兩個(gè)額外的屬性:index和input。index表示匹配項(xiàng)在字符串的位置,input表示應(yīng)用正則表達(dá)式的字符串。在數(shù)組中,第一項(xiàng)是與整個(gè)模式匹配的字符串,其他項(xiàng)是與模式中的捕獲組匹配的字符串,如果模式中沒有捕獲組,則該數(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'
[注意]對于exec()方法而言,即使在模式中設(shè)置了全局標(biāo)志(g),它每次也只會返回一個(gè)匹配項(xiàng)。在不設(shè)置全局標(biāo)志的情況下,在同一個(gè)字符串上多次調(diào)用exec(),將始終返回第一個(gè)匹配項(xiàng)的信息;而在設(shè)置全局標(biāo)志的情況下,每次調(diào)用exec()都會在字符串中繼續(xù)查找新匹配項(xiàng)。IE8-在lastIndex屬性上存在偏差,即使在非全局模式下,lastIndex屬性每次也會變化
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'var text = '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'var text = '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); }//["1", "3", "4", "2", "2", "4", "2", "3", "4", "3", "2", "4", "1"] [1, 3, 4, 5, 8, 9, 11, 12, 13, 16, 18, 19, 21]console.log(valueArray,indexArray); test()
接受一個(gè)字符串參數(shù),在模式與該參數(shù)匹配的情況下返回true,否則返回false
[注意]常用于只想知道目標(biāo)字符串與某個(gè)模式是否匹配,但不需要知道其文本內(nèi)容的情況,經(jīng)常用在if語句中
var text = '000-00-000';var pattern = //d{3}-/d{2}-/d{4}/;if(pattern.test(text)){ console.log('The pattern was matched');}模式匹配方法
String類型定義了幾個(gè)用于在字符串中匹配模式的方法
match()
只接受一個(gè)參數(shù),正則或字符串,把匹配的內(nèi)容保存到一個(gè)數(shù)組中返回
[注意]加上全局標(biāo)記時(shí),match()方法返回值中沒有index和input屬性
[1]不加/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'
[2]加/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
[3]字符串
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' search()
只接受一個(gè)參數(shù),正則或字符串,返回匹配的內(nèi)容在字符串中首次出現(xiàn)的位置,類似于不能設(shè)置起始位置的indexOf,找不到返回-1
[1]正則(加/g和不加/g效果一樣)
var string = 'cat,bat,sat,fat';var pattern = /.at/;var pos = string.search(pattern);console.log(pos);//0
[2]字符串
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] replace()
該方法接收兩個(gè)參數(shù):第一個(gè)為正則表達(dá)式或字符串(待查找的內(nèi)容)、第二個(gè)為字符串或函數(shù)(替換的內(nèi)容)
[1]字符串替換
var string = 'cat,bat,sat,fat';var result = string.replace('at','ond');console.log(result);//'cond,bat,sat,fat' [2]正則無/g替換
var string = 'cat,bat,sat,fat';var result = string.replace(/at/,'ond');console.log(result);//'cond,bat,sat,fat'
[3]正則有/g替換
var string = 'cat,bat,sat,fat';var result = string.replace(/at/g,'ond');console.log(result);//'cond,bond,sond,fond'
[4]函數(shù)替換
在只有一個(gè)匹配項(xiàng)(即與模式匹配的字符串的情況下,會向這個(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è)字符串
var string = 'cat,bat,sat,fat';var index = 0;var result = string.replace(/at/g,function(match,pos,originalText){ index++; if( index== 2){ return 'wow'; }else{ return '0'; }});console.log(result);//'c0,bwow,s0,f0' [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>'));//同上 split()
這個(gè)方法可以基于指定的分隔符將一個(gè)字符串分割成多個(gè)字符串,并將結(jié)果放在一個(gè)數(shù)組中,分隔符可以是字符串,也可以是一個(gè)RegExp。該方法可以接受第二個(gè)參數(shù)(可選)用于指定數(shù)組的大小,如果第二個(gè)參數(shù)為0-array.length范圍內(nèi)的值時(shí)按照指定參數(shù)輸出,其他情況將所有結(jié)果都輸出
[注意]IE8-對split()中的正則表達(dá)式,會忽略捕獲組
[tips]如果是split(''),則原來的數(shù)組會一個(gè)字符字符分割后傳出來
var colorText = 'red,blue,green,yellow';console.log(colorText.split(''));//["r", "e", "d", ",", "b", "l", "u", "e", ",", "g", "r", "e", "e", "n", ",", "y", "e", "l", "l", "o", "w"]console.log(colorText.split(','));//["red", "blue", "green", "yellow"]console.log(colorText.split(',',2));//["red", "blue"]console.log(colorText.split(//,/));//["red", "blue", "green", "yellow"]console.log(colorText.split(/e/));//["r", "d,blu", ",gr", "", "n,y", "llow"]console.log(colorText.split(/[^/,]+/));//將除去逗號以外的字符串變?yōu)榉指舴鸞"", ",", ",", ",", ""],IE8-會識別為[",",",",","] 局限性
下列為ECMAScript正則表達(dá)式不支持的特性
[1]匹配字符串開始的結(jié)尾的/A和/Z錨(但支持以^和$來匹配字符串的開始和結(jié)尾)
[2]向后查找(但支持向前查找)
[3]并集和交集類
[4]原子組
[5]Unicode支持(單個(gè)字符除外)
[6]命名的捕獲組(但支持編號的捕獲組)
[7]s(single單行)和x(free-spacing無間隔)匹配模式
[8]條件匹配
[9]正則表達(dá)式注釋
常見實(shí)例
[1]兩種方法找出字符串中所有的數(shù)字
[a]用傳統(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()將無法排除空格 if(!isNaN(value)){ temp += str1.charAt(i); }else{ if(temp != ''){ array.push(temp); temp = ''; } }}if(temp != ''){ array.push(temp); temp = ''; }console.log(array);//["1", "342", "24", "234", "3", "24", "1"] [b]用正則表達(dá)式
var str1 = 'j1h342jg24g234j 3g24j1';array = str1.match(//d+/g);console.log(array);//["1", "342", "24", "234", "3", "24", "1"]
[2]敏感詞過濾(replace方法的函數(shù)匹配)
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);//***是** [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);//["2015年7月28日", "2015年7月28日", "2015年7月28日", "2015年7月28日", "2015年7月28日", "2015年7月28日"] [4]獲取網(wǎng)頁中的文本內(nèi)容
var str = '<p>refds</p><p>fasdf</p>'var pattern = /<[^<>]+>/g;console.log(str.replace(pattern,''));//refdsfasdf
[5]去除首尾空格的trim()兼容寫法
var string = ' my name is littlematch ';console.log(string.replace(/^/s+|/s+$/,''));//my name is littlematch
關(guān)于JavaScript類型系統(tǒng)之正則表達(dá)式 的全部內(nèi)容就給大家介紹到這里,希望本文所述能夠幫助到大家。
新聞熱點(diǎn)
疑難解答