Home > Software engineering >  Regex for 3 digits and 3 Characters "123aBc", "1A2b3c", "abc123", &quo
Regex for 3 digits and 3 Characters "123aBc", "1A2b3c", "abc123", &quo

Time:08-19

I need help with regex which can match 3 digits and 3 characters in string irrespective of any order. eg. "123abc", "1a2b3c", "abc123", "11a4bc", "1ab23c", "1abc23". It could be in any order.

And also I need regex for "1A2B3C" or "1a2b3c".

CodePudding user response:

You could use the regex:

/(?=(?:.*\d){3})(?=(?:.*[a-zA-Z]){3})^[a-zA-Z\d]{6}$/
  • At least 3 digits anywhere in the string

    (?=(?:.*\d){3})
    
  • At least 3 alphabets anywhere in the string

    (?=(?:.*[a-zA-Z]){3})
    
  • Total string length should be 6

    ^[a-zA-Z\d]{6}$
    

Here's a snippet:

const check = str => /(?=(?:.*\d){3})(?=(?:.*[a-zA-Z]){3})^[a-zA-Z\d]{6}$/.test(str);

[ 
  // valid
  "123abc",
  "1a2b3c",
  "abc123",
  "11a4bc",
  
  // invalid
  "abcd12",
  "ab1234",
  "abc1234"
].forEach(str => console.log(str, check(str)))

CodePudding user response:

I wouldn't uses a regex but itself. But its pretty easy to create a utility function e.g.:

function chars3AndDigits3(input: string){
    return input.length === 6 
        && input.match(/\d/g)?.length === 3 
        && input.match(/[A-Za-z]/g)?.length === 3;
}

console.log(chars3AndDigits3('helloo')); // false
console.log(chars3AndDigits3('hel333')); // true
console.log(chars3AndDigits3('h3l3e3')); // true
  • Related