views:

696

answers:

3

I want to write a RegEx to pull out all the variable values and their names from the variable declaration statement. Say i have

int i,k = 10,l=0

i want to write a regex something like int\s^,?|(^,?)* but this will also accept k = 10 i.e. (without int preceding it) Basically idea is If string starts with int then get the variable list seperated by ,

i know to extract csv values, but here my string has some initial value as well. How can i resolve it?

A: 

You could build up your regular expression from the C# Grammar. But building a parser would certainly be better.

Gumbo
+1  A: 

Start thinking about the structure of a definition, say,

(a line can start with some spaces) followed by,

(Type) followed by

(at least one space)
(variable_1)
(optionally
   (comma // next var
    |
    '='number // initialization
    ) ...`

then try to convert each group:

^      \s*    \w+           \s+        \w+         ?          (','    |  '=' \d+   ) ...
line  some    type          at least  var          optionally   more  or init some
start spaces  (some chars)  one space (some chars)              vars     val  digits

Left as homework to remove spaces and fix up the final regex.

dirkgently
A: 

thanks guys. I'l build on the idea provided. bye

Anirudh Goel
Don’t you want accept an answer?
Gumbo