Home > Software engineering >  Regex - Allow one or two alphabet and its can be at anywhere in string
Regex - Allow one or two alphabet and its can be at anywhere in string

Time:10-24

I want regex which can fulfill below requirement:

  1. Between 6 and 10 total characters
  2. At least 1 but not more than 2 of the characters need to be alpha
  3. The alpha characters can be anywhere in the string

We have tried this but not working as expected : (^[A-Z]{1,2}[0-9]{5,8}$)|(^[A-Z]{1}[0-9]{4,8}[A-Z]{1}$)|(^[0-9]{4,8}[A-Z]{1,2}$)|([^A-Z]{3}[0-9]{6,9})

Can anyone please help me to figure it out?

Thanks

CodePudding user response:

You can assert the length of the string to be 6-10 char.

Then match at least a single char [A-Z] between optional digits, and optionally match a second char [A-Z] between optional digits.

^(?=[A-Z\d]{6,10}$)\d*[A-Z](?:\d*[A-Z])?\d*$
  • ^ Start of string
  • (?=[A-Z\d]{6,10}$) Positive lookahead to assert 6-10 occurrences of A-Z or a digit
  • \d*[A-Z] Match optional digits and then match the first [A-Z]
  • (?:\d*[A-Z])? Optionally match optional digits and the second [A-Z]
  • \d* Match optional digits
  • $ End of string

See a regex demo.

CodePudding user response:

One option is to use the following regular expression:

^(?=.*[a-z])(?!(?:.*[a-z]){3})[a-z\d]{6,10}$

with the case-indifferent flag i set.

Demo

This expression reads, "Match the beginning of the string, assert the string contains at least one letter, assert the string does not contain three letters and assert the string contains 6-10 characters, all being letters or numbers".

The various parts of the expression have the following functions.

^              # match the beginning of the string
(?=            # begin a positive lookahead
  .*[a-z]      # match zero or more characters and then a letter
)              # end positive lookahead
(?!            # begin a negative lookahead
  (?:          # begin a non-capture group
    .*[a-z]    # match zero or more characters and then a letter
  ){3}         # end non-capture group and execute it 3 times
)              # end negative lookahead
[a-z\d]{6,10}  # match 6-10 letters or digits
$              # match end of string

Note that neither of the lookaheads advances the string pointer maintained by the regex engine from the beginning of the string.

  • Related