1

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

Mike
  • 4,041
  • 6
  • 20
  • 37
  • Possible duplicate: https://stackoverflow.com/questions/17779744/regular-expression-to-get-a-string-between-parentheses-in-javascript – Aldert Sep 14 '18 at 05:15
  • @Aldert This is a C# question how can you make it a duplicate of a javascript question? Please remove your flags – Zeeshan Adil Sep 14 '18 at 05:19
  • @Shahrier, this is because I am looking for a good solution for you and this would be regex, especially when you have parenthisis in perenthises. I did not even look at the language. – Aldert Sep 14 '18 at 05:22
  • 1
    If you just remove the parentheses you get `2X+4++4`. Am I correct that you want only 1 plus between the two 4's? What if it's not plusses but other operators? – Hans Kilian Sep 14 '18 at 05:25
  • What would happen if you had `2X+4+(2+2X+(3X+7X)+4X)+4`? Is that possible to get? – Enigmativity Sep 14 '18 at 05:56

3 Answers3

1

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
Mrinal Kamboj
  • 11,300
  • 5
  • 40
  • 74
1

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                                                                        ^
Slava Utesinov
  • 13,410
  • 2
  • 19
  • 26
0

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.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172