How to get snippets between () a string

0

I'm doing a program that reads any math expression such as x^(3*x+1) + (cos x) , does not necessarily have to be that expression, and I'd like to know how to get the specific snippet between strings in the string.  I know that with IndexOf and substring I can get what is inside the first parentheses, but when I have more than 1 I do not know what to do.

EDIT: What I want to do is to get the string that is between the parentheses in the 3*x + 1" e "cos x case, but I do not know how to get the contents of the second parenthesis, cos x , since I only know how to do this using indexof and substring this way:

        string formula = Console.ReadLine();
        string trecho;
        int pos1, pos2;
        pos1 = formula.IndexOf('(');
        pos2 = formula.IndexOf(')');

        trecho = formula.Substring(pos1 + 1 , pos2 - 1);
        Console.WriteLine($"{trecho}");

I would like to know if there is any way to get the snippet that is in the second parenthesis as well.

    
asked by anonymous 24.08.2018 / 15:37

2 answers

1

If you just want to get what's inside parentheses (by removing the parentheses themselves) you can use the following regular expression:

string formula = Console.ReadLine();
string trecho = Regex.Match(formula, @"(?<=\().+?(?=\))").Value;

Console.WriteLine($"{trecho}");

You can try this regular expression at Regular Expressions 101 .

    
25.08.2018 / 13:33
0

try this:

        string formula = Console.ReadLine();
        List<string> trechos = new List<string>();

        int indexParenteses = formula.IndexOf('(');

        while (indexParenteses != -1)
        {
            trechos.Add(formula.Substring(indexParenteses + 1, formula.IndexOf(')', indexParenteses) - indexParenteses - 1));
            indexParenteses = formula.IndexOf('(', indexParenteses + 1);
        }

        trechos.ForEach(p => Console.WriteLine(p));
        Console.Read();
    
28.08.2018 / 14:17