skip to Main Content

I need to check that a string input contains exactly 2 special characters and 1 number.

is this the correct regex for this job?

(?=(.*[`!@#$%^&*-_=+'/.,]){2})

this is only checking special characters and not numbers.

I tried the regex above and it is not checking numbers

2

Answers


  1. Please find below your regex:

    const regex = /^(?=.*[!@#$%^&*()-=_+{}[]|\;:'",.<>/?])(?=.*d).*[!@#$%^&*()-=_+{}[]|\;:'",.<>/?].*[!@#$%^&*()-=_+{}[]|\;:'",.<>/?].*d.*$/;
    const input = "Your str**ing input here1";
    const isValid = regex.test(input);
    console.log(isValid)
    

    (?=.*[!@#$%^&*()-=_+{}[]|\;:'",.<>/?]) asserts that there is at least one special character present, and (?=.*d) asserts that there is at least one digit present. The rest of the regular expression ensures that there are exactly 2 special characters and 1 number present in the string.

    Login or Signup to reply.
  2. You can use this instead:

    /^(?=.*[!@#$%^&*()-_=+'/.\,].*[!@#$%^&*()-_=+'/.\,])(?=.*d).*$/
    

    and here is the test case to test the regex as per your requirement.

    function verifyString(inputString) {
      const regexPattern = /^(?=.*[!@#$%^&*()-_=+'/.\,].*[!@#$%^&*()-_=+'/.\,])(?=.*d).*$/;
      return regexPattern.test(inputString);
    }
    
    // Example usage:
    const testString1 = "ab@cde$1";
    const testString2 = "abcde123";
    
    console.log(verifyString(testString1)); // true
    console.log(verifyString(testString2)); // false
    

    I hope it works for you!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search