查找最外括号内的字符串

Find String Inside Outermost Parenthesis

假设我有一个包含多组括号和嵌套括号的字符串。我只想提取遇到的第一个括号中的字符串,包括它包含的任何嵌套括号。

例如:

this (is(maybe)) a test (and maybe not)

我要提取:

is(maybe)

我相信这可以在不使用正则表达式的情况下完成,我可以轻松地做到这一点。

所以我的问题是如何在没有 正则表达式的情况下实现这一点?

伪代码:

 iterate over chars
 if char is (
   increment counter
   store position of first ( only
 if char is )
   decrement counter
   if counter == 0
      use index of current char and position of first ( to get substring

为了避免伪代码成为唯一的答案,我自己使用标准算法来回答这个问题。给定 const string foo{ "this (is(maybe)) a test (and maybe not)" } 可以这样求解:

const auto start = find(cbegin(foo), cend(foo), '(');
const auto finish = find_if(start, cend(foo), [count = 0](const char i) mutable {
    if (i == '('){
        count++;
    }
    else if (i == ')'){
        count--;
    }
    return count <= 0; });

从这里开始,如果 startfinish 都不是 cend(foo),则该字符串有效并且可以从 string(next(start), finish) (Live Example) 获得。

这可能与 C++ 中的解决方案一样好。我想这只是一厢情愿的想法,那里有一些东西可以匹配括号并找到值。