删除C代码注释的脚本
发表于 : 2008-11-21 20:15
为了便于统计代码行数,写了个去掉代码注释的脚本,perl的。
顺便问一下,正则表达式怎么表达向前的“懒惰”的匹配,比如“aaaxxxb”中,我想匹配最短的"a.*b",即“axxxb”,"a.*?b"还是会把整个都匹配到,这里a可以理解为一个模式,不然我用"a[^a]*b"就可以了。
代码: 全选
#!/bin/perl -w
#Remove comments in c/c++ source file
#Usage: removecomment.pl Infile [Outfile]
use strict;
if(@ARGV < 1)
{
print STDERR "removecomment.pl Infile [Outfile]\n";
exit;
}
my ($infile,$outfile) = @ARGV;
open (FI,"$infile") || die "Can not open file:$!";
my @lines = <FI>;
close (FI);
my $contents = join '',@lines;
$contents =~ s/((?<=\n)|^)[ \t]*\/\*.*?\*\/\n?|\/\*.*?\*\/|((?<=\n)|^)[ \t]*\/\/[^\n]*\n|\/\/[^\n]*//gs;
if(!(defined($outfile)))
{
print $contents;
}
else
{
open (FO,">$outfile") || die "Can not open file:$!";
print FO $contents;
close (FO);
}