javascript中的正則表達式

javascript中的正則表達式

字面量
var reg=/\bis\b/g
var reg=//

var reg=/\bis\b/;
eg:'is a is c'.replace(reg,'IS');
構造函數
var reg=new RegExp('\\bis\\b','g')


var reg=new RegExp('\\bis\\b','g');
eg:'is a ls iss is'.replace(reg,'ABC')
正則表達式由兩種基本字符類型組成:
原義文本字符
a
元字符
有特殊含義的非字母字符
/b
* +? $ ^ .| \ () {} []
\f \t \cX
字符類
ab
咱們可使用元字符[]來構建一個簡單類[abc]其中之一
eg:'a1b2c3b4'.replace(/[abc]/g,'X');
字符類取反
^反向類/負向類
eg:'a1b2c3b4'.replace(/[^abc]/g,'X');
範圍類
[a-z] [a-zA-Z]
[1-10]
eg:'1233adfcADFAF'.replace(/[a-zA-Z]/g,'-')
預約義類
.回車換行外的全部字符
\d
\D
\s
\S
\w
\W非單詞字符
邊界匹配
^
$
\b
\B
eg:'this is a boy'.replace(/\bis\b/g,'0');
eg:'this is a boy'.replace(/is/g,'0');javascript

量詞
\d{3,6}java

eg:'123456'.replace(/\d{3,6}?/,'x')非貪婪匹配
分組
(is)  (is|a|k)
eg:'sis our is is ousi'.replace(/(is)/g,'x')
反向引用
eg:'2015-12-25'.replace(/(\d{4})-(\d{2})-(\d{2})/g,'$3/$2/$1')
"25/12/2015"正則表達式

前瞻
\w(?=\d)正則加斷言
eg:'a2*3'.replace(/\w(?=\d)/g,'哈啊')函數

後顧
js屬性
global
ignoreCase
multiline
var reg=/\w/;
reg.global;
reg.ignoreCase;
reg.multiline
reg.source
方法
test(str)this

eg:var reg=/\w/g;
while(reg.test('ab')){
console.log(reg.lastIndex);
}
exec(str)
var reg=/.\w(\d)/g;
eg:var str='a1234r342t3435';
reg.exec(str);spa

split()
eg:'a1b2c3d4'.split(/\d/g);
replace()
replace(str,replaceStr)
replace(reg,replaceStr)
replace(reg,function)

function會在每次匹配替換的時候調用
有四個參數
1.匹配字符串
2.正則表達式分組內容,沒有分組則沒有該內容
3匹配項在字符串中的index;
4原字符串3d

eg:'aosod3f4g5'.replace(/(\d)/, function (match, group, index, normal)
    {   console.log(match + 'match');
    console.log(group + 'group');  
    console.log(index + 'index');  
    console.log(normal + 'normal');
    });orm

相關文章
相關標籤/搜索