Search code examples
regexregex-group

How to create a conditional RegEx to check product input?


I want to write a simple regular expression to validate a product code as input from the user.

This product code has some rules to be respected as below:

  • 1group: (S)
  • 2group: (B|S|T|M)
  • 3group: (20)
  • 4group: (-)
  • 5group: (0|1) -> option '1' is valid when group number 2 is option T or M, for B and S shall be '0'

To match those conditions, I have created this regex:

(S)([B|S|T|M])(20)(-)([0|1])

Input to be tested:

  • SS20-0 => OK
  • SS20-1 => NOK
  • ST20-0 => OK
  • ST20-1 => OK

Great, it works partially, but how can I create a special condition into group 5 to check those rules? enter image description here


Solution

  • X15_Light,

    Here you go:

    (S)((B|S)|(T|M))(20)(-)(?(3)0|(0|1))
    

    (Demo)

    The conditional group structure looks like this:

    (?(1)Pattern1|Pattern2)
    

    Where (1) is a reference to a group. If group 1 returns a match then match Pattern1 else match Pattern2.