正則表達式(Regular Expression)是一種描述字符模式的對象,RegExp 對象表示正則表達式,用來驗證用戶輸入。
一,創建正則表達式
1,采用new運算符
var bb=new RegExp('參數字符串','可選模式修飾符')
2,字面量法
var bb=/參數字符串/可選模式修飾符;
模式修飾符參數
i 忽略大小寫
g 全局匹配
m 多行匹配
二,RegExp相關方法
test()在字符串中查找指定正則表達式,返回true或false
exec()在字符串中查找指定正則表達式,成功返回包含該查找字符串的相關信息數組,執行失敗則返回null
var pattern = new RegExp('Box','i'); //創建正則表達式,不區分大小寫,等效於var pattern=/Box/i
var str ='this is a box';
document.write(pattern.test(str));//true
document.write(pattern.exec(str));//box
//使用一條語句 document.write(/Box/i.test('this is a box'));
三,字符串的正則表達式方法
1.match(pattern)返回pattern中的子串或null
例
var pattern = new RegExp('Box','ig');
var str ='this is a box,TAH Is A box too';
document.write(str.match(pattern));//box,box
document.write(str.match(pattern).length);//2
2.replace(pattern,'replacement')用replacement替換pattern
例
var pattern = new RegExp('Box','ig');
var str ='this is a box,TAH Is A box too';
document.write(str.replace(pattern,'oo'));//this is a oo,TAH Is A oo too
3.search(pattern)返回字符串中pattern開始位置
例
var pattern = new RegExp('Box','i');
var str ='this is a box,TAH Is A box too';
document.write(str.search(pattern));//10找到就返回,不需要g
split(pattern)返回字符串按指定的pattern拆分的數組
var pattern = new RegExp(' ','i');
var str ='this is a box,TAH Is A box too';
document.write(str.split(pattern));//this,is,a,box,TAH,Is,A,box,too
四,正則表達式元字符
元字符是包含特殊含義的字符,可以控制匹配模式的方式
1.單個字符和數字
. 除換行符以外的任何字符
[a-z0-9]匹配括號中字符集中的任意字符
[^a-z0-9]匹配不在括號中的任意字符
\d 匹配數字
\D 匹配非數字,同[^1-9]
\w匹配字母和數字及_
\W匹配非字母和數字及_
2.空白字符
\0 匹配null字符
\b 匹配空格字符
~
3.錨字符
^行首匹配
$行尾匹配
\A 只有匹配字符串開始處
\b匹配單詞邊界,詞在[]內時無效
\B匹配非單詞邊界
\G匹配當前搜索的開始位置
\Z匹配字符串結束處或行尾
\z只匹配字符串結尾處
4.重復字符
x? 匹配一個或0個x
x*匹配0個或任意多個x
x+匹配至少一個x
(xyz)+匹配至少一個(xyz)
x{m,n}匹配最少m個,最多n個
5.替代字符
this|where|logo 匹配this或where或logo中任意一個
6.記錄字符
(string) 用於反向引用的分組
\1或$1 \2或$2 \3或$3 匹配第n個分組中的內容