Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

regex - Regular expression for nested C structs

I am trying to write a regex to solve the below C struct for one of our requirement. I am parsing the C structure file. In that I will have child and parent struct. The child will inherit parent struct members. I want the output, which consists of struct members and there length for further processing

INPUT:

#define  Len1  10;
#define  Len2  20;
#define  Len3   3;
#define  Len4   4;

typedef struct
{
char CHAR1           [Len1];
char CHAR2           [Len2];
} MyParent;


typedef struct
{

MyParent base;
char CHAR3        [Len3];
char CHAR4          [Len4];

} MyChild;

In the above I have to get: below OUTPUT:

 CHAR1 10
 CHAR2 20
 CHAR3 3
 CHAR4 4

The Perl Script will be really helpfull;

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You changed the problem after I gave my answer. It's not big of a deal though because the answer is not that much more complicated. You remember what you see in the #defines and use them later:

while( <DATA> ) {
    if( /^#defines+(w+)s+(d+)/ ) {
        $Len{$1} = $2;
        }
    elsif( /^chars/ ){
        s/(?<=CHARd)s+//;
        s/;$//;
        s/(?<=[)(w+)(?=])/ $Len{$1} || $1 /e;
        print;
        }
    }

This is a pretty trivial problem. Are you sure there's something that you aren't telling us? You don't need to do anything fancy. Skip all the lines that you want to ignore, and fixup the remaining lines to match your output needs:

while( <DATA> ) {
    next unless /^chars/;
    s/(?<=CHARd)s+//;
    s/;$//;
    print;
    }

__DATA__
#define  Len1  10;
#define  Len2  20;
#define  Len3   3;
#define  Len4   4;

typedef struct
{
char CHAR1           [Len1];
char CHAR2           [Len2];
} MyBase;


typedef struct
{

MyBase base;
char CHAR3          [Len3];
char CHAR4          [Len4];

} MyStruct;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...