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

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

问题描述

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

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)

提取:


是(可能)

is(maybe)

我相信这可以在不使用正则表达式的情况下完成,我可以很容易地做到。

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

所以我的问题是如何可以完成 / em> regexes?

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

推荐答案

Lest伪代码是我自己使用标准算法:

Lest pseudo code be the only answer I've taken it upon myself to answer this using standard algorithms:

const string foo{ "this (is(maybe)) a test (and maybe not)" };
const auto start = find(foo.cbegin(), foo.cend(), '(');
const auto finish = find_if(start, foo.cend(), [](char i){
    static auto count = 0;

    if (i == '('){
        count++;
    }
    else if (i == ')'){
        count--;
    }
    return count <= 0; });

从这里,如果开始完成都不是 foo.cend()字符串是有效的,可以从 string(next(start),finish)获取 href =http://ideone.com/5Nkx8p =nofollow> Live Example )。

From here, if both start and finish are not foo.cend() 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天全站免登陆