Search code examples
regexbashsystem-administration

Regular expression to accept a capital letter should accept a number instead


I have a regular expression which should accept a number in the final M position, but my customer has a letter instead (capital M).

CNTCST79L20H50MG

The regular expression is:

^[A-Za-z]{6}[0-9]{2}[A-Za-z]{1}[0-9]{2}[A-Za-z]{1}[0-9]{3}[A-Za-z]{1}$

How could I modify the regular expression so it will accept CNTCST79L20H50MG, instead of requiring a number?

is

^[A-Za-z]{6}[0-9]{2}[A-Za-z]{1}[0-9]{2}[A-Za-z]{1}[0-9]{2}[A-Za-z]{2}$

correct as a regular expression for the code

CNTCST79L20H50MG?

Edit:

NOTE Unfortunately, the final regular expression should accept both cases.


Solution

  • Yes, that is correct. You can see it working here: https://regex101.com/r/rHBFnA/1

    Updated for your update :)

    You can inidicate both letters and numbers in the character class:

    ^[A-Za-z]{6}[0-9]{2}[A-Za-z]{1}[0-9]{2}[A-Za-z]{1}[0-9]{2}[A-Za-z0-9][A-Za-z]$
    

    That matches both of these:

    CNTCST79L20H50MG
    CNTCST79L20H505G
    

    But not this:

    CNTCST79L20H5057
    

    https://regex101.com/r/rHBFnA/4