获取非条件部分的子串 [英] Get the substring of the non conditional part

查看:17
本文介绍了获取非条件部分的子串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个字符串,例如:
2X+4+(2+2X+4X)+4
括号的位置可以变化.我想知道如何提取没有括号的部分.例如我想要2X+4+4.有什么建议?我正在使用 C#.

I have this string for example:
2X+4+(2+2X+4X) +4
The position of the parenthesis can vary. I want to find out how can I extract the part without the parenthesis. For example I want 2X+4+4. Any Suggestions? I am using C#.

推荐答案

试试这个:

var str = "(7X+2)+2X+4+(2+2X+(3X+3)+4X)+4+(3X+3)";

var result =                                           
    str
        .Aggregate(
            new { Result = "", depth = 0 },
            (a, x) => 
                new
                {
                    Result = a.depth == 0 && x != '(' ? a.Result + x : a.Result,
                    depth = a.depth + (x == '(' ? 1 : (x == ')' ? -1 : 0))
                })
        .Result
        .Trim('+')
        .Replace("++", "+");

//result == "2X+4+4"

这会处理嵌套的、前面的和结尾的括号.

This handles nested, preceding, and trailing parenthesis.

这篇关于获取非条件部分的子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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