OL Learn

Regex Pattern (If Then Else)

I need to capture a value based on a pattern match, but also based on a priority. Thinking of an If Then Else.


For example I need to return CBS-19K49 or first match using ([a-zA-Z]{3}-[A-Za-z0-9]{5}) if it is available, but if it is not available then return ABC-10R0349 or first match using ([a-zA-Z]{3}-[A-Za-z0-9]{7})

Eventually I may need to add another match such as PBS-20-0524 or first match using ([a-zA-Z]{3}-[0-9]{2}-[A-Za-z0-9]{4})

Can’t quite get what I’m looking for.



Tagging @Phil on this one…Regex…you dream! :wink:

So your list of priorities needs to match the following order:

  1. Any XXX-XXXXX, then if not found,
  2. any XXX-XXXXXXX, then if not found
  3. any XXX-XX-XXXX

Is that it?

Yes, pretty close, but would be the first match if there are multiples of each pattern.

I honestly don’t think this can be done in a single RegEx expression: you want to look ahead and look back simultaneously, only capturing the first instance of a group that may or may not have been captured already…

It would be way easier (and much more manageable!) to just script it with 3 separate RegExes:

var r1 = /^[a-z]{3}-[a-z0-9]{5}$/gmi;
var r2 = /^[a-z]{3}-[a-z0-9]{7}$/gmi;
var r3 = /^[a-z]{3}-[a-z0-9]{2}-[a-z0-9]{4}$/gmi;

Run the first one, check for matches. If none, run the second one, etc.

I was worried that I was trying to get it too much into a single expression.

I’ll take this approach instead.