Home > OS >  My Regexp doesnt work correctly, but work on the regexr website
My Regexp doesnt work correctly, but work on the regexr website

Time:12-25

I've a problem with my regex. I dont know why, it's really strange but, I obtain some great result with console.log and not with my condition.

This is my code :

    const regEx = new RegExp("((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!\"#$%&'()* ,-./:;<=>?@[\\]^_\`{|}~]).{" k "})", 'g');
    let possibilities = 0;
    for(let i = 0; i < string.length; i  ){
        if(string.length<i k) break;
        const s = string.slice(i, i k);
        console.log(regEx.test(s), s)
        if(regEx.test(s)) possibilities  ;
    }
    return possibilities;

function count(n, k, string) {
    const regEx = new RegExp("((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!\"#$%&'()* ,-./:;<=>?@[\\]^_\`{|}~]).{" k "})", 'g');
    let possibilities = 0;
    for(let i = 0; i < string.length; i  ){
        if(string.length<i k) break;
        const s = string.slice(i, i k);
        console.log(regEx.test(s), s)
        if(regEx.test(s)) possibilities  ;
    }
    return possibilities;
}
console.log(count(30,6,"G=d:Dl:T=9NS1c$9qC%,^EdUVLnU-7"))

On my function, I get 0 possibilities, whereas I should receive 11. And when I count the true values of the consoles.log, I get 11 ... Do you know why I've this problem, and how I can solved it ?

And, when I test all the string on regexr, it's work...

CodePudding user response:

When you're doing console.log(regEx.test(s), s) you're consuming the RegEx once and move an internal cursor or something.

You need to create the new RegExp inside the loop scope, so its cursor will be placed back at the begining and won't be consumed at each iterations.

Plus, you may want to store the result in a variable if you want to use it twice or more :

function count(n, k, string) {
    
    let possibilities = 0;
    for(let i = 0; i < string.length; i  ){
        const regEx = new RegExp("((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!\"#$%&'()* ,-./:;<=>?@[\\]^_\`{|}~]).{" k "})", 'g');
        if(string.length<i k) break;
        const s = string.slice(i, i k);
        const regexResult = regEx.test(s);
        console.log(regexResult, s)
        if(regexResult) possibilities  ;
    }
    return possibilities;
}
console.log(count(30,6,"G=d:Dl:T=9NS1c$9qC%,^EdUVLnU-7"))

  • Related