简体   繁体   English

正则表达式查找某个函数的所有调用,而不是其声明

[英]Regex to find all calls of the certain function and NOT its declaration

I need to write a regex which will match only lines with the C function call, not its declaration. 我需要编写一个仅与C函数调用匹配的正则表达式,而不与它的声明匹配。

So, I need it to match only lines, where funcName() is not preceeded by int , double , float , char etc. and an arbitrary number of spaces. 因此,我需要它只匹配intdoublefloatchar等开头的funcName()以及任意数量的空格。


The problem is, I can run into following expressions: 问题是,我会遇到以下表达式:

printf("Hello"); int f() {return 1;};

So I must consider even the situation, where there are some other characters before the date-type name. 因此,即使在日期类型名称前还有其他一些字符的情况下,我也必须考虑。

myStruct f();

In this situation I want regex to match it, ONLY basic data-types should be excluded. 在这种情况下,我希望正则表达式匹配它,仅应排除基本数据类型。


So far I've got to this expression: 到目前为止,我已经了解了这个表达式:

^(?!(void|int|double|char))\s*f\(\).*$

But I have no idea, how to take care of the situation with characters before the type name. 但是我不知道如何使用类型名称前的字符来处理这种情况。

The following regex meets your specs: 以下正则表达式符合您的规格:

(^|((^|\s)(?!(void|int|double|char))[^\s]+)\s+)([a-zA-Z_]+\(\)?)
  • The function name is defined by a character class containing letters and the underscore. 函数名称由包含字母和下划线的字符类定义。
  • The line starts with the function call, or 该行以函数调用开头,或者
  • the line contains at least one non-whitespace character before the function name. 该行在函数名称之前至少包含一个非空格字符。 In that case ... 在这种情况下 ...
    • this non-WS sequence does not match the excluded keywords 此非WS序列与排除的关键字不匹配
    • there is at least 1 WS character before the function name 函数名称前至少有1个WS字符

See the live demo at regex101 . 请参阅regex101上的现场演示。

Caveat 警告

As several commentors have noted, this is not a robust solution . 正如一些评论者所指出的那样, 这不是一个可靠的解决方案 It will work for a tightly constrained set of function call and declaration patterns only. 它仅适用于严格限制的一组函数调用和声明模式。

A general regex-based solution (if possible at all, which would heavily depend on the regex engine features available) will be of theoretical interest only as it had to mimic completely the C preprocessor. 通用的基于正则表达式的解决方案(如果可能的话,将在很大程度上取决于可用的正则表达式引擎功能)仅在必须完全模仿C预处理程序的情况下才具有理论上的意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM