Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

My Regexp doesnt work correctly, but work on the regexr website

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

And, when I test all the string on regexr, it’s work…

>Solution :

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"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading