在最外括号内查找字符串 [英] Find String Inside Outermost Parenthesis

查看:27
本文介绍了在最外括号内查找字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

例如:

这(是(也许))一个测试(也许不是)

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

我要提取:

是(也许)

我相信这可以在不使用正则表达式的情况下完成,通过它我可以轻松做到.

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?

推荐答案

以免伪代码成为我自己使用标准算法回答这个问题的唯一答案.鉴于 const string foo{ "this (is(maybe)) a test (and may not)" } 可以这样解决:

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)" } c++14 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; });

从这里开始,如果 startfinish 都不是 cend(foo) 字符串是有效的,可以从 获得字符串(下一个(开始),完成)(现场示例).

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).

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

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.

这篇关于在最外括号内查找字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆