0

I am new to regular expressions. I am working on a code in C# where I need to calculate the number of variables in a mathematical function. I store those variables in a list. Currently I am using the following regular expression:

foreach (Match match in Regex.Matches(inputFunction, "[a-zA-Z]"))
{
    variables.Add(match.Value);
}

The problem is that I don't want to add functions like Sin, Cos, Tan to the list. I only need to extract variables. For example if the user enters Sin(x), then I only need to add 'x' in variables list.

Ben
  • 2,433
  • 5
  • 39
  • 69
user3367327
  • 15
  • 2
  • 6
  • @l.b The post marked as duplicate seems to be totally unrelated to this question, as this is not about evaluating the expressions, but rather parse it and extract certain parts. – jpw Jul 20 '15 at 23:32
  • @jpw no you are wrong.... – EZI Jul 20 '15 at 23:32
  • @EZI Please explain? – jpw Jul 20 '15 at 23:33
  • @jpw See "LB"s answer.... – EZI Jul 20 '15 at 23:33
  • @EZI I did. Ok, I read up a bit on what NCalc can do and it should be useful to do what the OP wants. Still don't think it's a duplicate question though. – jpw Jul 20 '15 at 23:39
  • @jpw so should we write the same answer here, just because the question is a little bit different. – EZI Jul 20 '15 at 23:42
  • @EZI Yes, there should possibly be a new answer here - not necessarily the same with minor adjustments. If the question is how to use regex to do a task, then maybe pointing to an answer requiring a third-party library isn't a perfect match. Maybe the OP can't use any external software and must do the parsing using regexes, who knows? I guess we'll just have to disagree. – jpw Jul 20 '15 at 23:46
  • 1
    @jwp, pure regex isn't enough. You need also a state machine. So the answer is: *you can't use regex* (at least there isn't a pure regex solution). But this other link can help OP more http://stackoverflow.com/questions/11593128/mathematical-expressions-parser – EZI Jul 20 '15 at 23:48
  • @EZI For the limited problem of extracting variables a regex might actually be enough, but sure, a proper parser would of course be better. Which might be what someone would have answered the OP if the question had still been open. :) – jpw Jul 20 '15 at 23:54
  • @jpw yes this someone would only repeat the previous answers :) – EZI Jul 20 '15 at 23:55
  • @EZI Fair enough. i can't cancel my reopen vote though, so maybe it will get reopened and closed again – jpw Jul 21 '15 at 00:06
  • @EZI Does NCAL have the feature to return the number of parameters though? The closest I could see was that it would fire EvaluateParameter if the parameter was not already defined in the dictionary. – Dijkgraaf Jul 21 '15 at 02:19

0 Answers0