Get the substring of the non conditional part

2019-07-07 19:46发布

问题:

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

回答1:

Try this one:

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.



回答2:

Try Regex approach:

var str = "(1x+2)-2X+4+(2+2X+4X)+4+(3X+3)";
var regex = new Regex(@"\(\S+?\)\W?");//matches '(1x+2)-', '(2+2X+4X)+', '(3X+3)'
var result = regex.Replace(str, "");//replaces parts above by blank strings: '2X+4+4+'
result = new Regex(@"\W$").Replace(result, "");//replaces last operation '2X+4+4+', if needed
//2X+4+4                                                                        ^


回答3:

Try simple string Index and Substring operations as follows:

string s = "2X+4+(2+2X+4X)+4";

int beginIndex = s.IndexOf("(");
int endIndex = s.IndexOf(")");

string firstPart = s.Substring(0,beginIndex-1);
string secondPart = s.Substring(endIndex+1,s.Length-endIndex-1);

var result = firstPart + secondPart;

Explanation:

  1. Get the first index of (
  2. Get the first index of )
  3. Create two sub-string, first one is 1 index before beginIndex to remove the mathematical symbol like +
  4. Second one is post endIndex, till string length
  5. Concatenate the two string top get the final result


标签: c# substring