Find String Inside Outermost Parenthesis

2019-01-29 07:45发布

Say that I have a string which contains both multiple sets and nesting of parenthesis. I want to extract only the string in the first parenthesis encountered, including whatever nested parenthesis it contains.

For example:

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

I want to extract:

is(maybe)

I believe this can be accomplished without the use of regexes, by which I can easily do it.

So my question is how can this be accomplished without regexes?

2条回答
狗以群分
2楼-- · 2019-01-29 08:21

Pseudo code:

 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
查看更多
劫难
3楼-- · 2019-01-29 08:43

Lest pseudo code be the only answer I've taken it upon myself to answer this using standard algorithms. Given const string foo{ "this (is(maybe)) a test (and maybe not)" } can be used to solve like this:

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; });

From here, if both start and finish are not cend(foo) the string is valid and can be obtained from string(next(start), finish) (Live Example).

It's possible that this is as good a solution as there is in C++. I guess it is just wishful thinking that there's something out there to match parentheses and find the value.

查看更多
登录 后发表回答