Home > Blockchain >  Regular expression 2 digits 10 letters/digits
Regular expression 2 digits 10 letters/digits

Time:10-04

I'm trying to make a regular expression, but something isn't working for me, the requirements are the following:

  1. Min length is 1
  2. Max length is 12
  3. The first 2 symbols must be numbers
  4. Next 10 must be either letters or numbers

This is what I have so far

/^[0-9]{0,2}[a-z][A-Z][0-9]{0,10}$/

Can you guys tell me what I'm doing wrong?

CodePudding user response:

Your pattern ^[0-9]{0,2}[a-z][A-Z][0-9]{0,10}$ matches 0, 1 or 2 digits at the start.

Then it matches 2 chars [a-z][A-Z] being a lowercase and an uppercase char A-Z which should be present in the string, and also makes the string length at least 2 chars.


You can make the second digit optional, and use 1 character class for the letters or numbers.

The length then has a minumum of 1, and a maximum of 12.

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

Regex demo

Or a version withtout a lookahead as suggested by @Scratte in the comments:

^\d(?:\d[A-Za-z\d]{0,10})?$

Regex demo

  • Related