Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to parse C++ enum

How can a regular expression be constructed to parse C++ enums? The enums I tried on looked like

enum Temperature
{
    C = 0,
    F=1,     // some elements are commented
    R,       // most elements are not gived a value
    K        // sometimes the last element is succeeded by a comma
} temperature;

// different indent style is used
enum Depth {
    m = 0,
    ft = 1,
} depth;

I tried several simple patterns but none is general enough to catch all cases above.

Any regexp wizard who can help me?

Edit: to clarify, I want the name and value, e.g. C and 0.

like image 262
Waws Avatar asked Nov 04 '22 15:11

Waws


1 Answers

That was challenging :) Below is the best I could come up with. Assuming it is given just the text between { and } it captures all names and corresponding values:

/(\w+)\s*(?:=\s*(\d+)|)\s*,?\s*(?:(?:\n|$)|\/\/.*?(?:\n|$)|)/
like image 143
nobody Avatar answered Nov 09 '22 14:11

nobody