使用正则表达式拆分字符串,忽略大括号内出现的定界符

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

假设我有一个字符串

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

我需要用 and 作为分隔符来拆分它,但前提是它不出现在大括号内

所以从上面的字符串我应该得到 5 个字符串:
Max, Bob, Merry, Jack and Co., Lisa.

我试过这样的模式:

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

但它不起作用 - JackCo. 仍然分开(我使用 C++,所以我必须两次转义特殊字符)。

{...}部分先匹配。即放在|.

左边
\{.*?\}|and

如果可能,它将匹配 {foo and bar},但如果不是,它将尝试匹配 and

这是一个可能的解决方案,部分基于 bobble-bubble 的评论。它将根据要求生成五个字符串,周围没有空格或大括号。

std::string text = "Max and Bob and Merry and {Jack and Co.} and Lisa";
std::regex re(R"(\}? +and +(?![^{]*\})\{?)");

std::sregex_token_iterator it(text.begin(), text.end(), re, -1);
std::sregex_token_iterator end;

while (it != end)
    std::cout << *it++ << std::endl;

我尽量保持简单,您可能想用完整的空白检测替换 and 周围的空格。提供交互式版本 here

如果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 {介于两者之间。

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

See this demo at regex101

需要根据需要进行转义或尝试像 @SMeyer 评论的原始字符串文字。