-1

I'm trying to parse this expression in C# like so:

fun(p1, p2, 33,"lina", g(x,5), ...)

How can I get the "type" of everything in the expression, given these examples:

fun    ---> function
p1, p2 ---> variables
33     ---> constant
"lina" ---> constant 
g      ---> function 
x      ---> variable
5      ---> constant 
lina20
  • 25
  • 5
  • You cannot use regex to get **"type"** of string. You need some kind of parser to transform this string to some kind of data structure. – tym32167 Oct 20 '16 at 19:06
  • Can you please elaborate as the data you provided is insufficient to understand your problem. – Amey Kamat Oct 20 '16 at 19:07

1 Answers1

2

In general case you can't parse such string with regular expression: regular expression can operate with regular grammar only (with some minor extensions), when you need context free one. You want a parser (e.g. Antlr or Irony). See

Regular vs Context Free Grammars

for details. To show the difficulties you can face, let's just play with strings and comments:

 fun (1 + p1 + 1);                  // p1 is an argument
 fun (/*1 + p1 + 1*/);              // p1 is NOT an argument
 fun ("/*1" + p1 + "1*/");          // p1 is an argument 
 fun (/*"/*1" + p1 + "1*+/"*/);     // p1 is NOT an argument 
 fun ("/*""/*1" + p1 + "1*+/""*/"); // p1 is an argument  
 ...
Community
  • 1
  • 1
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • is correct. You need something more akin to an interpreter/parser than just a simple regex. – JamesFaix Oct 20 '16 at 19:23
  • Ok, you posted what OP cannot do. But, would be better, imho, for OP, to suggest something, how he can solve his problem, probably in different way. – tym32167 Oct 20 '16 at 19:23
  • @tym32167: parsing is not an easy walk, but you're quite right: when stating that "X is not a solution", an aternative "Y can be used" should be provided. I can't see an easy way to marriage good old Lex/Yacc/Bison with .net, so I've mentioned Antlr and Irony – Dmitry Bychenko Oct 20 '16 at 19:40