定義
正則又叫規則或模式,是一個強大的字符串匹配工具。javascript通過RegExp類型來支持正則表達式
特性
[1]貪婪性,匹配最長的
[2]懶惰性,不設置/g,則只匹配第1個
寫法
perl寫法(使用字面量形式)
var expression = /pattern/flags;
模式(pattern)部分可以是任何簡單或復雜的正則表達式,可以包含字符串、限定類、分組、向前查找以及反向引用。每個正則表達式可以帶一個或多個標志(flags),用以標明正則表達式的行為。正則表達式支持三個標志:
[1]g:表示全局模式(global)
[2]i:表示不區分大小寫(ignoreCase)
[3]m:表示多行模式(multiline)
//匹配字符串所有'at'的實例var pattern1 = /at/g;
RegExp構造函數
RegExp構造函數接收兩個參數:要匹配的字符串模式(pattern)和標志字符串(flags)(可選)
[注意]RegExp構造函數的兩個參數都是字符串。且使用字面量形式定義的任何表達式都可使用構造函數
//匹配字符串所有'at'的實例var pattern = new RegExp('at','g');
兩種寫法的區別
字面量寫法不支持變量,只能用構造函數的形式來寫
[tips]獲取class元素(因為classname是變量,只能使用構造函數的形式)
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中,正則表達式字面量始終共享同一個RegExp實例,而使用構造函數創建的每一個新RegExp實例都是一個新實例。ES5中規定使用正則字面量必須像直接調用RegExp構造函數一樣,每次都創建新的RegExp實例
語法
[注意]正則表達式中不能出現多余空格
元字符(14個)
() [] {} / ^ $ | ? * + .
[注意]元字符必須轉義,即用/ 加轉義字符,用new RegExp寫的正則必須雙重轉義
轉義字符
. 除換行符/n之外的任意字符
/d 數字
/D 非數字
/w 字母、數字、下劃線
/W 非字母、數字、下劃線(漢字不屬于/w)
/s 空格
/S 非空格
/b 邊界符(/w的左側或右側不是/w,則會出現一個邊界符)
/B 非邊界符
/1 表示和前面相同的一個字符
/t 制表符
/v 垂直制表符
/uxxxx 查找以十六進制xxxx規定的Unicode字符(/u4e00-/u9fa5代表中文)
(/w)(/d)/1/2 :/1代表/w當時所代表的值,/2代表/d當時所代表的值
[注意]正則表達式中的子項必須是用小括號括起來的,并且順序以小括號的前括號出現的順序為準
[tips]找出重復項最多的字符和個數
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"
系統轉義
alert()和console.log()里面的字符是系統轉義字符
/0 空字節
/n 換行
/t 制表
/b 空格
/r 回車
/f 進紙
// 斜杠
/' 單引號
/" 雙引號
/xnn 以十六進制nn表示一個字符(n為0-f),如/x41表示'A'
/unnnn 以十六進制nnnn表示一個Unicode字符(n為0-f),如/u03a3表示希臘字符ε
[注意]alert里面的換行不能用<br>或<br/>,而應該用/n
alert('http://www.baidu.com/n/t你好')
雙重轉義
由于RegExp構造函數的參數是字符串,所以某些情況下,需要對字符進行雙重轉義。所有元字符必須雙重轉義,已經轉義過的字符也必須雙重轉義
字面量模式 -> 等價的字符串//[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次
? 相當于{0,1}
* 相當于{0,}
+ 相當于{1,}
位置符號
^ 起始符號
$ 結束符號
?= 肯定正向環視
?! 否定正向環視
控制符號
[] 候選
| 或
^ 非
- 到
(red|blue|green) 查找任何指定的選項
[abc] 查找方括號之間的任何字符
[^abc] 查找任何不在方括號之間的字符
[0-9] 查找任何從0到9的數字
[a-z] 查找任何從小寫a到小寫z的字符
[A-Z] 查找任何從大寫A到大寫Z的字符
[A-z] 查找任何從大寫A到小寫z的字符
[adgk] 查找給定集合內的任何字符
[^adgk] 查找給定集合外的任何字符
$符號
$$ $
$& 匹配整個模式的子字符串(與RegExp.lastMatch的值相同)
$` 匹配子字符串之前的子字符串(與RegExp.leftContext的值相同)
$' 匹配子字符串之后的子字符串(與RegExp.rightContext的值相同)
$n 匹配第n個捕獲組的子字符串,其中n等于0-9。$1表示匹配第一個捕獲組的子字符串(從第1個算起)
$nn 匹配第nn個捕獲組的子字符串,其中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,
構造函數屬性
適用于作用域中的所有正則表達式,并且基于所執行的最近一次正則表達式操作而變化。關于這些屬性的獨特之處在于可以通過兩種方式訪問它們,即長屬性名和短屬性名。短屬性名大都不是有效的ECMAScript標識符,所以必須通過方括號語法來訪問它們
長屬性名 短屬性名 說明
input $_ 最近一次要匹配的字符串
lastMatch $& 最近一次的匹配項
lastParen $+ 最近一次匹配的捕獲組
leftContext $` input字符串中lastMatch之前的文本
multiline $* 布爾值,表示是否所有表達式都使用多行模式
rightContext $' Input字符串中lastMarch之后的文本
使用這些屬性,可以從exec()方法或text()方法執行的操作中提取出更具體的信息
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個用于存儲捕獲組的構造函數屬性。RegExp.$1/RegExp.$2/RegExp.$3……到RegExp.$9分別用于存儲第一、第二……第九個匹配的捕獲組。在調用exec()或test()方法時,這些屬性會被自動填充
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}
實例屬性
通過實例屬性可以獲知一個正則表達式的各方面信息,但卻沒多大用處,因為這些信息都包含在模式聲明中
global: 布爾值,表示是否設置了g標志
ignoreCase: 布爾值,表示是否設置了i標志
lastIndex: 整數,表示開始搜索下一個匹配項的字符位置,從0算起
multiline: 布爾值,表示是否設置了標志m
source: 正則表達式的字符串表示,按照字面量形式而非傳入構造函數中的字符串模式返回
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()三個方法,且都返回正則表達式字面量,與創建正則表達式的方式無關。要注意的是toString()和toLocaleString()返回的正則表達式的字符串表示,而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
實例方法
exec()
專門為捕獲組而設計,接受一個參數,即要應用模式的字符串。然后返回包含第一個匹配項信息的數組。在沒有匹配項的情況下返回null。返回的數組包含兩個額外的屬性:index和input。index表示匹配項在字符串的位置,input表示應用正則表達式的字符串。在數組中,第一項是與整個模式匹配的字符串,其他項是與模式中的捕獲組匹配的字符串,如果模式中沒有捕獲組,則該數組只包含一項
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()方法而言,即使在模式中設置了全局標志(g),它每次也只會返回一個匹配項。在不設置全局標志的情況下,在同一個字符串上多次調用exec(),將始終返回第一個匹配項的信息;而在設置全局標志的情況下,每次調用exec()都會在字符串中繼續查找新匹配項。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()
接受一個字符串參數,在模式與該參數匹配的情況下返回true,否則返回false
[注意]常用于只想知道目標字符串與某個模式是否匹配,但不需要知道其文本內容的情況,經常用在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類型定義了幾個用于在字符串中匹配模式的方法
match()
只接受一個參數,正則或字符串,把匹配的內容保存到一個數組中返回
[注意]加上全局標記時,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()
只接受一個參數,正則或字符串,返回匹配的內容在字符串中首次出現的位置,類似于不能設置起始位置的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()
該方法接收兩個參數:第一個為正則表達式或字符串(待查找的內容)、第二個為字符串或函數(替換的內容)
[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]函數替換
在只有一個匹配項(即與模式匹配的字符串的情況下,會向這個函數傳遞3個參數:模式的匹配項、模式匹配項在字符串中的位置、原始字符串。在正則表達式定義了多個捕獲組的情況下,傳遞給函數的參數依次是模式的匹配項、第一個捕獲組的匹配項、第二個捕獲組的匹配項……第N個捕獲組的匹配項,但最后兩個參數仍然分別是模式的匹配項在字符串中的位置和原始字符串,這個函數返回一個字符串
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()
這個方法可以基于指定的分隔符將一個字符串分割成多個字符串,并將結果放在一個數組中,分隔符可以是字符串,也可以是一個RegExp。該方法可以接受第二個參數(可選)用于指定數組的大小,如果第二個參數為0-array.length范圍內的值時按照指定參數輸出,其他情況將所有結果都輸出
[注意]IE8-對split()中的正則表達式,會忽略捕獲組
[tips]如果是split(''),則原來的數組會一個字符字符分割后傳出來
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(/[^/,]+/));//將除去逗號以外的字符串變為分隔符["", ",", ",", ",", ""],IE8-會識別為[",",",",","]
局限性
下列為ECMAScript正則表達式不支持的特性
[1]匹配字符串開始的結尾的/A和/Z錨(但支持以^和$來匹配字符串的開始和結尾)
[2]向后查找(但支持向前查找)
[3]并集和交集類
[4]原子組
[5]Unicode支持(單個字符除外)
[6]命名的捕獲組(但支持編號的捕獲組)
[7]s(single單行)和x(free-spacing無間隔)匹配模式
[8]條件匹配
[9]正則表達式注釋
常見實例
[1]兩種方法找出字符串中所有的數字
[a]用傳統字符串操作
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]用正則表達式
var str1 = 'j1h342jg24g234j 3g24j1';array = str1.match(//d+/g);console.log(array);//["1", "342", "24", "234", "3", "24", "1"]
[2]敏感詞過濾(replace方法的函數匹配)
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]獲取網頁中的文本內容
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
關于JavaScript類型系統之正則表達式 的全部內容就給大家介紹到這里,希望本文所述能夠幫助到大家。
新聞熱點
疑難解答