Home > database >  Regex for combination of alphnumeric letters which has at least 2 uppercase letter or 1 number?
Regex for combination of alphnumeric letters which has at least 2 uppercase letter or 1 number?

Time:05-01

I need a regex for combination of numbers and uppercase letters and maybe lowercase letters and /,- characters, which contains at least 4 characters.

But of course it should contain at least 2 uppercase letter or one number.

I tried this:

barcode_regex = r"(?=(?:. [A-Z]))(?=(?:. [0-9]))([a-zA-Z0-9/-]{4,})"

For example match such cases as follows:

ametFXUT0
G197-6STK
adipiscXWWFHH
A654/9023847
HYJ/54GFJ
hgdy67h

CodePudding user response:

You could use a single lookahead to assert at least 4 characters, and the match either a single digit or 2 uppercase chars in the allowed ranges.

^(?=.{4})(?:[A-Za-z/,-]*\d|(?:[a-z\d/,-]*[A-Z]){2})[A-Za-z\d/,-]*$

Explanation

  • ^ Start of string
  • (?=.{4}) Assert 4 charcters
  • (?: Non capture group
    • [A-Za-z/,-]*\d Match optional allowed characters without a digit, then match a digit
    • | Or
    • (?:[a-z\d/,-]*[A-Z]){2} Match 2 times optional allowed characters withtout an uppercase char, then match an uppercase char
  • ) Close non capture group
  • [A-Za-z\d/,-]* Match optional allowed characters
  • $ End of string

See a regex demo.

CodePudding user response:

You could use two lookaheads combined via an alternation to check for 2 uppercase or 1 number:

^(?:(?=.*[A-Z].*[A-Z])|(?=.*\d))[A-Za-z0-9/-] $

Demo

This regex patterns says to:

^
(?:
    (?=.*[A-Z].*[A-Z])  assert that 2 or more uppercase are present
    |                   OR
    (?=.*\d)            assert that at least one digit is present
)
[A-Za-z0-9/-]           match any alphanumeric content (plus forward slash or dash)
$
  • Related