Js-正則表達式學習(4)Tips小結

1.n$

      n$作用是以n單位字符串爲結尾,可以明確的是單個字符n,也可以是一個單位字符串,比如(ab\w)$

 

2.(n)\1(b)\2  正向引用(需要括號)

    \1~\n可以作爲,n和b的引用,注意,n和b都需要使用()括起來,用帶括號的才能被引用,n和n和上一條一樣,也是單個字符或者單位字符串

var str = "AABCD";
var regexp = /(\w)\1/g;
var res = str.match(regexp);
console.log(res);//['AA']

3.$1$2    反向引用(需要括號)

    $1~$n可以作爲當前RegExp的匹配分組的各個引用,例子中ABD被引用了,但由於\w沒有使用(),所以不算引用

var str = "ABCD";
var regexp = /(A)(B)\w(D)/g;
var res = str.replace(regexp,"$3");
console.log(res);//D
console.log(RegExp.$1);//A
console.log(RegExp.$2);//B
console.log(RegExp.$3);//D

4.[\s\S] ,[\w\W],[\d\D]表示所有字符

 

5.lastIndex 和 regexp.exec(str);可以逐步查看匹配項

var str = "123Li456LI789";
var regexp = /Li/ig;
console.log(regexp.lastIndex);//0
console.log(regexp.exec(str));//[ 'Li', index: 3, input: '123Li456LI789', groups: undefined ]
console.log(regexp.lastIndex);//5
console.log(regexp.exec(str));//[ 'LI', index: 8, input: '123Li456LI789', groups: undefined ]
console.log(regexp.lastIndex);//10
console.log(regexp.exec(str));//null

6.str.replace的使用

一般使用str.replace(str,str1);只是一次替換,不能全局替換

正則使用str.replace(regexp,str);雖然正則,但是不能調配或者使用正則中的引用

正則加函數使用 str.replace(regexp,($1~$n)=>{return out});

var str = "123Li456lI789";
var regexp = /(l)(i)/ig;
var res = str.replace("Li", "LI");//一般使用
str.match(regexp);
console.log(res);//123LI456lI789 
res = str.replace(regexp, "LI");//正則使用,可以替換兩個Li
console.log(res);//123LI456LI789 
res = str.replace(regexp, function () {
    console.log(arguments[0]);//“Li”匹配的字符串
    console.log(arguments[1]);//L第一個引用
    console.log(arguments[2]);//i第二個引用
    console.log(arguments[3]);//3最後一個引用的下一個
    var temp = arguments[1].toLowerCase();
    return temp + arguments[2];
}
);
console.log(res);//123li456lI789
//正則使用,可以動態任意修改匹配的內容

7.限定某個字符串只能由什麼組成,使用/^n$/g

例子:用戶名只 能用 中文、英文、數字、下劃線、4-16個字符。

var reg = /^[\u4E00-\u9FA5\w]{4,16}$/g;
var res = str.match(reg);

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章