通过python正则表达式匹配C语言中的指针变量和指针函数

网上看到的相关题目,尝试自己做一下,仅供自己参考。
import re

str_demo = r"""#include <stdio.h>
// 返回两个字符串中较长的一个
char *func(char *str1, char *str2){
    if(strlen(str1) >= strlen(str2)){
        return str1;
    }else{
        return str2;
    }
}
int main(){
    char *s1 = "C Language";
    char *s2 = "C is very great!";
    char *longstr = func(s1, s2);
    printf("Long string: %s\n", longstr);
    return 0;
}"""

# 以下匹配指针变量。(int|char|float):定义类型。\s+:匹配变量类型后的空格1-无穷个空格。(\*[_a-zA-Z0-9]+):匹配*开头,由下划线,下小写字母和数字组成的变量名。[;|,|\s+|\)]:匹配结尾是;或,或空格或)的字符串。
print(re.findall(r"(int|char|float)\s+(\*[_a-zA-Z0-9]+)[;|,|\s+|\)]", 'int  *_ab ; char *pa, float *__c_c,'))
print(re.findall(r"(int|char|float)\s+(\*[_a-zA-Z0-9]+)[;|,|\s+|\)]", str_demo))

# 以下匹配指针函数。末尾\(:结尾是(开头的,是指针函数
print(re.findall(r"(int|char|float)\s+(\*[_a-zA-Z0-9]+)\(", str_demo))
# 返回二维数组x[*][0]是变量类型,x[*][1]是指针变量名

执行结果:

C:\Python37\python.exe D:/Python3_workspace/test/regular.py
[('int', '*_ab'), ('char', '*pa'), ('float', '*__c_c')]
[('char', '*str1'), ('char', '*str2'), ('char', '*s1'), ('char', '*s2'), ('char', '*longstr')]
[('char', '*func')]

 




posted @ 2022-06-02 23:43  毛毛虫也疯狂  阅读(264)  评论(0编辑  收藏  举报