How do I get rid of an entire match if capture group a equals capture group b

Viewed 28

My goal is to try and capture a group unless my second capture group equals my third capture group.

e.g. "example 1 when a, b" here I want my first capture group to be the first number my second capture group to be the a before the comma and my third capture group to be the b after the comma. In the scenario of "example 2 when a,a" I would like the regex to capture nothing.

I have a solution that will just not recognize the second a, capture group 3, but it still captures the "example 1 when a" part. I need to just discard the entire capture if capture group 2 is equal to capture group 3.

/example\s+([1-9]+)\s+(?:when\s+([a-z])(\s*,\s*(?!\2)[a-z])?)?/gi

This captures "example 12 when a" still. This almost does what I need by not capturing the part that I don't want but it still captures something. I would like the regex to capture nothing in the scenario where \2 is equal to \3.

1 Answers

You can use

/example\s+([1-9][0-9]*)(?:\s+when\s+([a-z])(?!\s*,\s*\2\b)(?:\s*,\s*[a-z])?)?\b/gi

See the regex demo.

The point is that the last part in your regex is optional, so the (?!\s*,\s*\2\b) is placed after the last obligatory part to be executed only once. Otherwise, backtracking fires and the match can still be found.

Related