0

I have a program in which the user can input various values, amongst which square root values. I've tried designing a system where if the user inputs sqrt(number), then the program will extract the number, then do Math.Sqrt() on that number, and then pass it back.

The main problem arises when the theoretical possibility of something like Sqrt(4) / Sqrt(5) comes along. Because then not only am I dealing with one sqrt() statement, but I have to deal with the second as well.

The pattern I've been using for Regex is this:

string Pattern = @"sqrt\((.*)\)";

How can I modify this pattern to allow for the possibility of multiple square roots due to fractions?

I was also told to perhaps look into creating a parser for this. Would this be an appropriate solution?

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
root
  • 125
  • 1
  • 10
  • 1
    See [duplicate](http://stackoverflow.com/questions/13844168/regex-non-greedy) for the solution to your immediate problem. If you want to write a parser, then research how to do so - that would be too broad to fit in a single Stack Overflow answer. – CodeCaster Sep 06 '16 at 12:47
  • The duplicate you've marked doesn't make sense to me. I don't understand how that answer can be applied in my context. – root Sep 06 '16 at 12:52
  • `.*?` instead of `.*` to make it non-greedy. – CodeCaster Sep 06 '16 at 12:53
  • Well, actually, that lazy dot matching might not work, use balanced construct: `string Pattern = @"sqrt\(((?>[^()]+|(?)\(|(?<-o>)\))*)(?(o)(?!))\)";` – Wiktor Stribiżew Sep 06 '16 at 13:57
  • Ok, can you please explain to me in detail what the heck that line of code does. – root Sep 07 '16 at 03:07

0 Answers0