如何用正则表达式匹配两段字符串长度之和为一个固定值

时间:2021-04-06 06:11:27
如何用正则表达式匹配两段字符串长度之和为一个固定值


happyhappyhappy123456789happy
happy12tgdfg789happyhappyhappy
happyhappy1sdf56789happyhappy

匹配这几种情况,删除中间的字符串

前后happy数之后不为4的不匹配

2 个解决方案

#1


或者简单点,如何用正则表达式匹配两段字符串长度之和为大于(或小于)某个固定值

#2



function check(str,matchstr,time){
        var reg=new RegExp(`^(?:.*?${matchstr}.*?){${time}}$`);
        return reg.test(str);
    }
    var arr=[
        'happyhappyhappy123456789happy',
        'happy12tgdfg789happyhappyhappy',
        'happyhappy1sdf56789happyhappy'
    ]
    console.log(arr.map(function(item){
        return check(item,'happy',3);
    }));
    console.log(arr.map(function(item){
        return check(item,'happy',4);
    }));
    console.log(arr.map(function(item){
        return check(item,'happy',5);
    }));

大于等于

#1


或者简单点,如何用正则表达式匹配两段字符串长度之和为大于(或小于)某个固定值

#2



function check(str,matchstr,time){
        var reg=new RegExp(`^(?:.*?${matchstr}.*?){${time}}$`);
        return reg.test(str);
    }
    var arr=[
        'happyhappyhappy123456789happy',
        'happy12tgdfg789happyhappyhappy',
        'happyhappy1sdf56789happyhappy'
    ]
    console.log(arr.map(function(item){
        return check(item,'happy',3);
    }));
    console.log(arr.map(function(item){
        return check(item,'happy',4);
    }));
    console.log(arr.map(function(item){
        return check(item,'happy',5);
    }));

大于等于