LoginSignup
8
9

More than 5 years have passed since last update.

C のソースコードからコメントと空行を削除する

Posted at

概要

C/C++ のソースコードからコメントと空行を削除したいなーってことありますよね?例えばコメントと空行以外の行数を数えたいときとか。そんなときに使うスクリプトです。今回は Perl を使い正規表現で置換しました。

スクリプト

rmcom.pl
#!/usr/bin/env perl

my $str = join('', <>);
my $comment_re = qr[(?:\A|(?<!\\))(?:/\*.*?\*/|//[^\r\n]*)]ms;
my $non_comment_re = qr[(?:\A|(?<!\\))((["'])(?:\\.|(?:(?!\2|\\).))*\2)]ms;

$str =~ s[$non_comment_re|$comment_re][$1]gms;
$str =~ s[$non_comment_re|[[:blank:]]+(?:(?=\r)|$)][$1]gms;
$str =~ s[$non_comment_re|^[\r\n]+][$1]gms;

print $str;

文字列リテラルの中を処理しないようにするため $non_comment_re の最初のキャプチャーグループをそのまま出力します。バックスラッシュによるエスケープも認識します。

使い方

rmcom.pl **/*.c | wc -l

などとすれば OK です。

8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9