Home > Back-end >  Regex matching digit and letters or only digits
Regex matching digit and letters or only digits

Time:11-03

I'm stuck trying to code a regex which match with those conditions:

  • string with more than 9 digits
  • string with more than 9 digits and letters

I can't figure out how to write my regex saying to it: digit or digit and letters can match but not letters.

Those string should match:

  • 12345678987654567
  • jhsjd4567hsqdgqsgh456786576567kj
  • 9l8j9n9k0n9n8n

Those string should not match:

  • loremipsum
  • a1
  • 12567

My regex so far: /(?:\w){9,}/

Thanks a lot :)

CodePudding user response:

I am interpreting your requirements as: match a string of more than nine characters which contains either digits only or digits and letters only.

const tests = [
  '12345678987654567',
  'jhsjd4567hsqdgqsgh456786576567kj',
  '9l8j9n9k0n9n8n',
  'loremipsum',
  'a1',
  '12567',
];

for (const t of tests) {
  console.log(t.padEnd(35)  
    /^(?=.*\d)[a-z\d]{10,}$/i.test(t)
  )
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

The positive lookahead (?=.*\d) ensures that there is at least one digit in the string.

Remove the i flag if you want to match only lower-case letters.

CodePudding user response:

Using \w can match both letters and digits, so using (?:\w){9,}, which can be written as \w{9,} can also match only letters or only underscores.

Reading the requirements, you can match 9 or more times a letter or a digit and make sure that the string does not contain only letters using a negative lookahead if that is supported.

If you want to match more than 9, you can use {10,} as the quantifier.

^(?![a-zA-Z] $)[a-zA-Z0-9]{9,}$

The pattern matches:

  • ^ Start of string
  • (?![a-zA-Z] $) Negative lookahead, assert not only characters a-z A-Z in the string
  • [a-zA-Z0-9]{9,} Match 9 or more times chars a-z A-Z or a digit
  • $ End of string

Regex demo

Or using word boundaries:

\b(?![a-zA-Z] \b)[a-zA-Z0-9]{9,}\b

Regex demo

CodePudding user response:

I believe it should work

/([a-z]*[0-9][a-z]*){9,}/
  • Related