c - 如何在 C 源代码中搜索简单的 if 语句?

标签 c regex search awk

我想在一组 C 源文件中搜索简单的 if 语句。

这些是以下形式的语句:

if (condition)
    statement;

任何数量的空白或其他序列(例如“} else”)都可能出现在 if 之前的同一行中。注释可能出现在“if(条件)”和“statement;”之间。

我想排除以下形式的复合语句:

if (condition)
{
    statement;
    statement;
}

我在 awk 中尝试了以下各项:

awk  '/if \(.*\)[^{]+;/ {print NR $0}' file.c    # (A) No results
awk  '/if \(.*\)[^{]+/ {print NR $0}' file.c    # (B)
awk  '/if \(.*\)/ {print NR $0}' file.c          # (C)

(B) 和 (C) 给出了不同的结果。两者都包括我正在寻找的项目和我想要排除的项目。显然,部分问题在于如何处理跨越多行的模式。

可以忽略边缘情况(格式错误的注释、奇怪的缩进或奇怪位置的大括号等)。

我怎样才能做到这一点?

最佳答案

基于 Al 的回答,但修复了几个问题(另外我决定也检查简单的 else 子句(此外,它打印完整的 if block ):

#!/usr/bin/perl -w

my $line_number = 0;
my $in_if = 0;
my $if_line = "";
#ifdef NEW
my $block = "";
#endif /* NEW */
# Scan through each line
while(<>)
{
    # Count the line number
    $line_number += 1;
    # If we're in an if block
    if ($in_if)
    {
        $block = $block . $line_number . "+ " . $_;
        # Check for open braces (and ignore the rest of the if block
        # if there is one).
        if (/{/)
        {
            $in_if = 0;
            $block =  "";
        }
        # Check for semi-colons and report if present
        elsif (/;/)
        {
            print $if_line;
            print $block;
            $block = "";
            $in_if = 0;
        }
    }
    # If we're not in an if block, look for one and catch the end of the line
    elsif (/(if \(.*\)|[^#]else)(.*)/)
    {
        # Store the line contents
        $if_line = $line_number . ": " .  $_;
        # If the end of the line has a semicolon, report it
        if ($2 =~ ';')
        {
            print $if_line;
        }
        # If the end of the line contains the opening brace, ignore this if
        elsif ($2 =~ '{')
        {
        }
        # Otherwise, read the following lines as they come in
        else
        {
            $in_if = 1;
        }
    }
}

关于c - 如何在 C 源代码中搜索简单的 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1078767/

相关文章:

从 ‘unsigned char’ 转换为 ‘int’ 可能会改变它的值

Javascript 正则表达式检查卡住网页

search - 如何知道 PDF 是否仅包含图像或已进行 OCR 扫描以进行搜索?

nhibernate - 使用 NHibernate 进行复杂搜索

搜索索引 Windows SMB 文件共享的解决方案

c - 使用 MPI_Bcast 时出现 MPI 段错误

c - 如何通过 C89 检查文件是否存在?

Java 正则表达式 : how to back-reference capturing groups in a certain context when their number is not known in advance

c - 用另一个结构的内容初始化一个结构

regex - 用于检查非空值和空字符串的正则表达式