How to pick up snippets between () a string

Asked

Viewed 446 times

0

I’m doing a program that reads some mathematical expression like for example x^(3*x+1) + (cos x), it doesn’t necessarily have to be that expression, and I’d like to know how to get the specific stretch between parentheses of the string. I know with IndexOf and substring I can take what’s inside the first parentheses, but when I’m over 1 I don’t know what to do.

EDIT : What I want to do is take the snippet of the string between the parentheses, in this case 3*x + 1" e "cos x, but I don’t know how to get the content of the second parenthesis, cos x, because I only know how to do it using indexof and substring in that 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 wonder if there is any way to take the stretch that is in the second parentheses also.

  • Hello, Renato, welcome to Sopt. O as is a problem of logic, not necessarily of programming... You can share with us that you have managed to magine so far as an algorithm, at least?

  • I edited the post with some more information

  • Unfortunately at the moment I can not answer your question, but I can comment. Friend you can achieve the result you want using regular expressions. Here’s a link with a little help. You can use this website to assist in understanding the syntax of regular expressions.

  • 1

    Thank you very much, I will give a study in these regular expressions, but that’s exactly what I was looking for

  • I know your question refers to picking up the expression within parentheses, but I believe you can solve this algorithm using stacks or some known techniques

  • Speak Brazilian, take the expression ai: https://regex101.com/r/KRZNu1/1

Show 1 more comment

2 answers

1

If you only want to get what is 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 on Regular Expressions 101.

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();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.