python删除C函数体

nic*_*ich 2 c python regex match substitution

我正在寻找如何从某些C源文件中的函数中删除整个实体的方法.

例如,我有这个内容的文件:

1.  int func1 (int para) {
2.    return para;
3.  }
4.
5.  int func2 (int para) {
6.    if (1) {
7.      return para;
8.    }
9.    return para;
10. }
Run Code Online (Sandbox Code Playgroud)

我试过这些正则表达式:

content = re.sub('(\{[.*]?\})', '', content, flags=re.DOTALL)
Run Code Online (Sandbox Code Playgroud)

但是嵌套{}存在问题.这个正则表达式只替换为first},因此第9行和第10行仍然在内容中.我认为解决方案应该在计数{和}括号并在计数器为0时停止替换.{is found => counter ++,} is found => counter--.但我不知道如何在python中实现它.你们能帮我一脚吗?

bta*_*bta 9

我想你正在尝试重新发明一种已经多次实施过的轮子.如果你想要的只是在C文件中提取每个函数的签名,那么有更简单的方法来完成它.

ctags实用程序将为您解决此问题:

~/test$ ctags -x --c-types=f ./test.c
func1            function      1 ./test.c         int func1 (int para) {
func2            function      5 ./test.c         int func2 (int para) {
~/test$ # Clean up the output a little bit
~/test$ ctags -x --c-types=f ./test.c | sed -e 's/\s\+/ /g' | cut -d ' ' -f 5-
int func1 (int para) {
int func2 (int para) {
Run Code Online (Sandbox Code Playgroud)