Home > Software engineering >  Multiple RegEx not working with conditions
Multiple RegEx not working with conditions

Time:03-28

I'm trying to use two RegEx.test() methods with Logical AND in a conditional block, however, not getting expected result.

const mobileRegEx = /[0][4-5][0-9]{8}/g;
const firstPhone = '0432779680';
const secondPhone = '0543000987';


if(mobileRegEx.test(firstPhone)  &&  mobileRegEx.test(secondPhone)){
    console.log(firstPhone, secondPhone); /* expecting this to be executed but it is not */
}

CodePudding user response:

A regular expression with the g (global) flag keeps track of the position of the last match, and keeps searching from the next position.

So this means that the first match will return the position on the first number, and then the second match will fail because instead of restarting from the start it will start from the position of the first match and miss.

The fix is to simply remove the g from your original expression like this

/[0][4-5][0-9]{8}/;

However, I also see that your expression might give false positives. For example, if you add random characters before and after the actual number, it will still match.

E.g.

firstPhone = 'WRONG0432779680WRONG';

Will still return true. If you're using this for validating a phone number format, you need to restrict the regex to the whole string passed. You can do so by using ^ at the beginning and $ at the end, to say this is the whole string.

So the regex should look like

const mobileRegEx = /^[0][4-5][0-9]{8}$/;

Here's the final code

const mobileRegEx = /^[0][4-5][0-9]{8}$/;
const firstPhone = '0432779680';
const secondPhone = '0543000987';
if(mobileRegEx.test(firstPhone)  &&  mobileRegEx.test(secondPhone)){
    console.log(firstPhone, secondPhone);
}

  • Related