Search code examples
regexregex-lookaroundsregex-group

Capture repetitive groups separated by optional and/or


here is the generalized pattern that I am struggling with

if condition1 and|or condition2 then action1 and|or action2

Condition as well as action generally has this pattern:
situation >= 10 or situationB = off|on

The problem is the repetitive and/or in condition/action, it could totally be absent (0 count of and/or) or as many (*).

example string:
situation >= 10 or situationB = off and situationC = on
situation = on

Here's something I tried but need some help:

^\s*(\w+)\s*(=|\>=)\s*(\d+|\w+)\s*(and|or)?

regex101 link

How can modify the regex so that it could group each of the conditions/actions that may or may not be separated by and/or?


Solution

  • You may try using the following regex pattern:

    (.*?)(?:\s+(?:and|or)|\s*$)
    

    Demo

    This matches in the first capture group all content in between possible and/or separators, including the final term until the end of the string.

    Note that if you are using a programming language, then an easier option might be to just split on \s*\b(?:and|or)\b\s*, which would yield an array/collection of matching terms.