Search code examples
regexregular-language

How to exclude 2 alphabetic character from a string in REGEX


I am trying to find the REGEX for this particular product code.

Description:

  1. A valid product code must begin by a one of two digit number.
  2. The number can't begin with 0
  3. The number must be followed by a hyphen -
  4. The hyphen is followed by a sequence of upper case letters conforming to the patterns AAA and BBB
  5. AAA: string of any three upper case alphabetic characters except "I" and "O"
  6. BBB string of any three upper case alphabetic characters in the range "A" to "D"

Examples:

  • N-AAA

  • NN-AAA

  • NN-BBB

  • NN-AAABBB

My problem is with the point 5) I mentioned. My solution so far is:

^[1-9]?[0-9]-[A-Z][^IO]{3}?[A-D]{3}$

I am not sure about the part that I highlighted in my RE. I am looking to know if my solution is correct and if it is not, I would like to know the answer and the reasoning behind it.

Thanks,


Solution

  • You have to use Negative Lookahead (?!([I]|[O])) in your Regex. Please check this:

    ^[1-9]{1}[0-9]+\-(?!([I]|[O]))[A-Z]{3}[A-D]{3}
    

    Old Update:

    ^[1-9]{1}[0-9]+\-((?!([I]|[O]))[A-Z]{3}[A-D]{3}|(?!([I]|[O]))[A-Z]{3}|[A-D]{3})
    

    Updated regex:

    ^[1-9]{1}(|[0-9])\-([A-HJ-NP-Z]{3}[A-D]{3}|[A-HJ-NP-Z]{3}|[A-D]{3})
    

    ^[1-9]{1} Start with 1 to 9

    (|[0-9]) N or NN

    \- hyphen (-)

    [A-HJ-NP-Z] Avoid I and O

    ([A-HJ-NP-Z]{3}[A-D]{3}|[A-HJ-NP-Z]{3}|[A-D]{3}) AAABBB or AAA or BBB

    You can check it in Regex101.

    Check my final update in Regex.