js正则记录

全局标志g

let reg=/^\d+$/g;
reg.test(123);    // true
reg.test(123);    // false

出现以上问题是因为reg的g属性,设置的全局匹配。RegExp有一个lastIndex属性,来保存索引开始的位置,当第一次执行以后,lastIndex为0,第二次调用以后变成了3,导致问题出现。解决办法:1.去掉g,2.在调用以后将lastIndex设为0

^的用法

1.作为开头标记

// 以test开头
let reg=/^test/;
let test1=reg.test('test111');    // true
let test2=reg.test('111test');    // false

2.取反

// 不以t开头  作为取反的时候必须在[]中
let reg=/^[^t]/;
let test1=reg.test('tes111');    // false
let test2=reg.test('111test');   // true

$的用法

// 以test结束
let reg=/test$/;
let test1=reg.test('tes111');
let test2=reg.test('111test');

split正则用法

let reg=/\s*,\s*/;
let str1='1,2,3';
str1.split(reg);    // [1,2,3]
let str2='a,\nb,\nc,\nd';
str2.split(reg);    // [a,b,c]
let str3='q\r\n  ,\r\n  r\r\n  ,\r\n  s';
str3.split(reg);    // [q,r,s]

\b(边界)的用法

// 可以捕获正整数 x 的值,末尾带有 x 的变量不应当被捕获
var reg=/\bx=\d+\b/;
let list=['x=5','abc x=5','fox=123','x=abc','x=33qw','3x=33','beep x=123123 boop'];
list.forEach(item=>{
    let result=item.match(reg);
    if(!result){
        console.log(result);
    }else{
        console.log(result[0].split('=')[1]);
    }
});
// 5,5,null,null,null,null,123123

分组的使用

let reg=/(\d{4})\/(\d{2})\/(\d{2})/;
let str='2019/12/26';
let date=str.replace(reg,'$1-$2-$3');  // 2019-12-26

引用

'2019-08-25'.match(/(\d{4})-(\d{2})-\2/)
// null

'2019-08-08'.match(/(\d{4})-(\d{2})-\2/)
// 不为null
// 最后一个  '\2'  是对第二个的引用

'2019-08-25'.replace(/(\d{4})-(\d{2})-(\d{2})/,`year($1),month($2)`)
// "year(2019),month(08)"
// $1,$2是对前两个匹配字符串的引用

贪婪与惰性

贪婪就是尽可能多的匹配,非贪婪就是尽可能少的匹配,默认贪婪,非贪婪就是量词后面加个?

let reg=/dx+?/;
let reg2=/dx+/;
'dxxxdxxx'.match(reg)[0];    // dx
'dxxxdxxx'.match(reg2)[0];  // dxxx

猜你喜欢

转载自www.cnblogs.com/jingouli/p/12091683.html