[英]How to use regex to find all array declarations in C files?
我正在尝试分析一些第三方代码,并且对给定源(.c和.h)中声明+定义的所有数组都感兴趣。 知道在移植到嵌入式系统时是否浪费了一些内存很有趣。
我可以假设仅使用标准类型,即char,int,long,float,double。
这是我要查找的示例:
char message[100];
int tag[MY_PERSONAL_TAG_SIZE];
double vald[2] ={1.0,1.1};
在同事的大力支持下,我尝试了以下方法,但得到了一些误报:
egrep -e '(char|int|long|short|float|double)[ \t]*[^ \t)]+[ \t]*\[[^ \t]+\]' *
这也会发现(不应该):
wordTable = &intTable[0];
MyFunction (MyPointer* foo, int *bar, int code[4], int add[4], char *Mystring[4]) {
我想正则表达式还会发现其他一些误报,并且可能会错过它应该找到的一些定义。 因此,我很高兴听到任何建议。 谢谢。
我建议使用clang-query
代替regex
。 这是一个显示clang-query
可以执行的示例。
两个文件test.h
和test.cpp
与问题类似。
$ cat ~/CPP/test.h
1 int x[10], y, z[10];
$ cat ~/CPP/test.cpp
1 #include "test.h"
2
3 #define MY_PERSONAL_TAG_SIZE 10
4
5 struct MyPointer;
6
7 void MyFunction (MyPointer* foo, int *bar, int code[4], int add[4], char *Mystring[4])
8 {
9 }
10
11 int main()
12 {
13 char message[100];
14 int tag[MY_PERSONAL_TAG_SIZE];
15 double vald[2] ={1.0,1.1};
16 int a[10], b, c[30];
17
18 return 0;
19 }
使用test.cpp
和查询数组声明运行clang-query
。
$ ./clang-query ~/CPP/test.cpp --
clang-query> help
Available commands:
match MATCHER, m MATCHER Match the loaded ASTs against the given matcher.
set bind-root (true|false) Set whether to bind the root matcher to "root".
set output (diag|print|dump) Set whether to print bindings as diagnostics,
AST pretty prints or AST dumps.
clang-query> match varDecl(hasType(arrayType()))
Match #1:
~/CPP/test.h:1:1: note: "root" binds here
int x[10], y, z[10];
^~~~~~~~~
Match #2:
~/CPP/test.h:1:1: note: "root" binds here
int x[10], y, z[10];
^~~~~~~~~~~~~~~~~~~
Match #3:
~/CPP/test.cpp:13:5: note: "root" binds here
char message[100];
^~~~~~~~~~~~~~~~~
Match #4:
~/CPP/test.cpp:14:5: note: "root" binds here
int tag[MY_PERSONAL_TAG_SIZE];
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Match #5:
~/CPP/test.cpp:15:5: note: "root" binds here
double vald[2] ={1.0,1.1};
^~~~~~~~~~~~~~~~~~~~~~~~~~~
Match #6:
~/CPP/test.cpp:16:5: note: "root" binds here
int a[10], b, c[30];
^~~~~~~~~
Match #7:
~/CPP/test.cpp:16:5: note: "root" binds here
int a[10], b, c[30];
^~~~~~~~~~~~~~~~~~~
7 matches.
clang-query>
这将需要一些正则表达式向导,但不够可靠 。 您应该为此类任务使用适当的C解析器。
但是,如果您想快速又脏乱地执行操作,以下是一个Perl(或与Perl兼容)的正则表达式可以解决这个问题(它需要与m
和s
修饰符一起使用):
(?:\(.*\)|\/\*.*?\*\/)(*SKIP)(?!)|(?:^|[;,])\s*\K(?:char|int|long|short|float|double)(?:\s*\**\s*\w+\s*\[\w*\]\s*[=;,])+
演示: http : //regex101.com/r/hY6sV2/3
它忽略注释或括号中的所有内容,并尝试在行的开头或冒号或分号之后找到数组声明。
尝试:
(?:char|int|long|short|float|double)(?:\s+.*?)?\[.*?\].*?;
如果满足以下条件,则此正则表达式符合要求:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.