Matching strings where multiple capture groups must be different in regex

Viewed 158

I am trying to create a regular expression that picks out a boolean algebra identity, specifically ((A+B).(A+C)), where A, B and C are different strings consisting of characters [A-Z]. I am running into problems getting the regular expression recognise that in the string I am looking for A != B != C. Here is what I have tried:

  • \(\(([A-Z]+)\+([A-Z])\)\.\(\1\+([A-Z])\)\)

however, even though I have put every string that I want to be different in a capturing group, it doesn't stop it from thinking that strings B and C are the same. This is because the regular expression matches for all three of the following strings:

  • ((A+B).(A+C))
  • ((A+B).(A+A))
  • ((A+A).(A+A))

while I only want it to match the first one.

1 Answers

You can use negative lookahead to make sure that group 2 is not the same as group 1, and that group 3 is not the same as either groups 1 or 2.

\(\(([A-Z]+)\+(?!\1)([A-Z])\)\.\(\1\+(?!\1)(?!\2)([A-Z])\)\)

Split up for readability:

\(\(
([A-Z]+)
\+
(?!\1)([A-Z])
\)\.\(
\1
\+
(?!\1)(?!\2)([A-Z])
\)\)

Inputs:

((A+B).(A+C))
((A+B).(A+A))
((A+A).(A+A))
((A+B).(A+B))

Matches:

((A+B).(A+C))

Try it on regex101

Related