Regex for retrieving function name and parameters

I am creating an application in which the user can specify an expression for some fields. The expression must also contain functions. I need to evaluate these expressions and display the final value in the report.

I had an expression to retrieve the function name and its parameters. Previously, function parameters were decimal. But now parameters can also be an expression.

For ex,

Round( 1 * (1+ 1 /100) % (2 -1), 0) Function-name : Round Parameter1 : 1 * (1+ 1 /100) % (2 -1) Parameter2 : 0 

Previous regex:

 string pattern2 = @"([a-zA-Z]{1,})[[:blank:]]{0,}\(([^\(\)]{0,})\)"; 

This regular expression no longer helps me find expression parameters.

Can someone help me with the correct regex to extract function name and parameters? I implement all or most of the functions supported by the Math class. The program is built in C #

Thanks in advance for your help.

+4
source share
3 answers
  "^\s*(\w+)\s*\((.*)\)" 

group (1) is the name of the function

divide the group (2) with "," , you will get a list of steam.

updated

since I don't have a Windows system (.Net either), I am testing it with python. Nested function is not a problem. if we add "^ \ s *" at the beginning of the expression:

 import re s="Round(floor(1300 + 0.234 - 1.765), 1)" m=re.match("^\s*(\w+)\s*\((.*)\)",s) m.group(1) Output: 'Round' m.group(2) Output: 'floor(1300 + 0.234 - 1.765), 1' you can split if you like: m.group(2).split(',')[0] Out: 'floor(1300 + 0.234 - 1.765)' m.group(2).split(',')[1] Out: ' 1' 

Well, if your nesting function is like f(a(b,c(x,y)),foo, m(j,k(n,o(i,u))) ) , my code will not work.

+2
source

You can try writing a parser instead of using regular expressions.
The Irony library (in my opinion) is extremely easy to use, and the examples have something very similar to what you are trying to do.

+1
source

From a Regex post to map functions and capture their arguments, you can retrieve your function by re-expressing Kent and use this code to extract parameters from the last group:

 string extractArgsRegex = @"(?:[^,()]+((?:\((?>[^()]+|\((?<open>)|\)(?<-open>))*\)))*)+"; var ArgsList = Regex.Matches(m.Groups[m.Groups.Count - 1].Value, extractArgsRegex); 
0
source

All Articles