skip to Main Content

I have this regex which checks if the password has one digit at least.

^(?=.*[0-9]).{6,}$

How do I modify the regex to check if the sum of all the digits in the password is equal to say 10.
So this string should match "dhbqdw46". This shouldn’t "jwhf1ejhjh0".

2

Answers


  1. Regular expressions are designed for pattern matching and cannot perform arithmetic operations like calculating the sum of digits.

    As mentioned in the comments, you’ll need to implement the logic yourself. Since you’ve tagged this question with JavaScript, here’s a solution using JavaScript:

    function isValidPassword(password, targetSum){
      const digits = password.match(/d/g) || [];
      const sum = digits.reduce((sum, digit) => sum + parseInt(digit, 10), 0);
      return sum === targetSum
    }
    
    
    const password1 = "dhbqdw46";
    const password2 = "jwhf1ejhjh0";
    
    console.log(isValidPassword(password1, 10));  // Output: true
    console.log(isValidPassword(password2, 10));  // Output: false
    Login or Signup to reply.
  2. RegEx can’t do that and is certainly not meant to do that. To check this kind of stuff you need to write your own JavaScript.

    If you want you can use regex to extract all digits from the string and then sum them up using JavaScript (See Variant 1) or you just use JavaScript and do not use regex at all (See Variant 2).

    Variant 1

    const isDigit = (character) =>
      typeof character === "string" &&
      character.length === 1 &&
      character >= "0" &&
      character <= "9";
    
    /**
     * Matches all digits in the password and returns them as an array of numbers.
     * @param {string} password
     * @returns all digits in the string as an array of numbers
     */
    const matchAllDigits = (password) =>
      [...password.matchAll(/d/g)].map((x) => parseInt(x[0]));
    
    /**
     * Sum up all numbers in the array.
     * @param {number[]} nums numbers to sum up
     * @returns total sum of all numbers
     */
    const sumOfDigits = (nums) => nums.reduce((acc, num) => acc + num, 0);
    
    /**
     * Return true if sum of digits matches provides sum, otherwise false.
     * @param {string} password password to check
     * @param {number} sum sum of digits to check for (default 10)
     * @returns
     */
    const hasSumOfDigits = (password, sum = 10) =>
      sumOfDigits(matchAllDigits(password)) === sum;
    
    console.log(hasSumOfDigits("dhbqdw46")); // true
    console.log(hasSumOfDigits("jwhf1ejhjh0")); // false

    Variant 2

    const isDigit = (character) =>
      typeof character === "string" &&
      character.length === 1 &&
      character >= "0" &&
      character <= "9";
    
    /**
     * Return true if sum of digits matches provides sum, otherwise false.
     * @param {string} password password to check
     * @param {number} sum sum of digits to check for (default 10)
     * @returns
     */
    const hasSumOfDigits = (password, sum = 10) => {
      let index = 0;
      let currentSum = 0;
      const chars = password.split("");
      // Loop through all characters in password as long as sum is not already exceeded
      while (index < chars.length && currentSum <= sum) {
        const currentChar = chars[index];
        if (isDigit(currentChar)) {
          // if character is digit, add it to current sum
          currentSum += parseInt(currentChar);
        }
        // go to next character
        index++;
      }
      // return true if sum of digits match provided sum, otherwise false
      return currentSum === sum;
    };
    
    console.log(hasSumOfDigits("dhbqdw46")); // true
    console.log(hasSumOfDigits("jwhf1ejhjh0")); // false
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search