js正则记录
2021-05-05 20:29
                         标签:oop   执行   res   item   用法   last   贪婪   str1   nbsp    全局标志g 出现以上问题是因为reg的g属性,设置的全局匹配。RegExp有一个lastIndex属性,来保存索引开始的位置,当第一次执行以后,lastIndex为0,第二次调用以后变成了3,导致问题出现。解决办法:1.去掉g,2.在调用以后将lastIndex设为0   ^的用法 1.作为开头标记 2.取反   $的用法   split正则用法   \b(边界)的用法   分组的使用   引用   贪婪与惰性 贪婪就是尽可能多的匹配,非贪婪就是尽可能少的匹配,默认贪婪,非贪婪就是量词后面加个? js正则记录 标签:oop   执行   res   item   用法   last   贪婪   str1   nbsp    原文地址:https://www.cnblogs.com/jingouli/p/12091683.htmllet reg=/^\d+$/g;
reg.test(123);    // true
reg.test(123);    // false
// 以test开头
let reg=/^test/;
let test1=reg.test(‘test111‘);    // true
let test2=reg.test(‘111test‘);    // false
// 不以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‘);
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]
// 可以捕获正整数 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
上一篇:bugku 程序员本地网站