Home > Blockchain >  Regex for an alphanumeric string of specific length with at least one letter and at least one digit
Regex for an alphanumeric string of specific length with at least one letter and at least one digit

Time:02-19

I want to match alphanumeric string of specific length with at least one letter and at least one digit.

For example, adfyg432 should contain alphabetic and digit and the length should start from 8.

I used this expression but it won't work:

^([A-Za-z]{1,}\d{1,}){8,}$

CodePudding user response:

Your current pattern repeats a group 8 or more times. That group by itself matches 1 or more chars a-z followed by 1 or more digits.

That means that the minimum string length to match is 16 chars in pairs of at least 2. So for example a string like a1aa1a1a1a1a1a1a1 would match.


You could write the pattern using 2 lookahead assertions to assert a length of at least 8 and assert at least a char a-z.

Then match at least a digit. Using a case insensitive match:

^(?=[a-z\d]{8,}$)(?=\d*[a-z])[a-z]*\d[a-z\d]*$

In parts, the pattern matches:

  • ^ Start of string
  • (?=[a-z\d]{8,}$) Positive lookahead, assert 8 or more chars a-z or digits till end of string
  • (?=\d*[a-z]) Positive lookahead to assert at least a char a-z
  • [a-z]* Match optional chars a-z
  • \d Match at least a single digit
  • [a-z\d]* Match optional chars a-z or digits
  • $ End of string

Regex demo

const regex = /^(?=[a-z\d]{8,}$)(?=\d*[a-z])[a-z]*\d[a-z\d]*$/i;
[
  "AdfhGg432",
  "Abc1aaa"
].forEach(s =>
  console.log(`Match "${s}": ${regex.test(s)}`)
)

  • Related