Search code examples
c++regexqregexp

Splitting a string with regex, ignoring delimiters that occur within braces


Suppose I have a string

Max and Bob and Merry and {Jack and Co.} and Lisa.

I need to split it with and being the delimiter, but only if it does not occur within curly braces.

So from the above string I should get 5 strings:
Max, Bob, Merry, Jack and Co., Lisa.

I tried something like this pattern:

[^\\\{.+]\\band\\b[^.+\\\}]

But it doesn't work - Jack and Co. are still split as well (I use C++ so I have to escape special characters twice).


Solution

  • If lookaheads are supported by the QRegExp you can check if inside braces by looking ahead at the final word boundary if there is a closing } with no opening { in between.

    \band\b(?![^{]*})
    

    See this demo at regex101

    Need to be escaped as desired or try the raw string literal like @SMeyer commented.