如果您要剥离“嵌套”的 cmets,即:
/* This is a comment
/* that has been re-commented */ possibly /* due to */
various modifications */
regexp 可能不是最好的解决方案。尤其是如果它像上面的示例那样跨越多行。
上次我不得不做这样的事情时,我一次读一行,记下“/*”(或特定语言的分隔符)有多少级别,并且不打印任何内容,除非计数为 0。
这是一个例子 - 我提前道歉,因为它是非常糟糕的 Perl,但这至少应该给你一个想法:
use strict;
my $infile = $ARGV[0]; # File name
# Slurp up input file in an array
open (FH, "< $infile") or die "Opening: $infile";
my @INPUT_ARRAY = <FH>;
my @ARRAY;
my ($i,$j);
my $line;
# Removes all kind of comments (single-line, multi-line, nested).
# Further parsing will be carried on the stripped lines (in @ARRAY) but
# the error messaging routine will reference the original @INPUT_ARRAY
# so line fragments may contain comments.
my $commentLevel = 0;
for ($i=0; $i < @INPUT_ARRAY; $i++)
{
my @explodedLine = split(//,$INPUT_ARRAY[$i]);
my $resultLine ="";
for ($j=0; $j < @explodedLine; $j++)
{
if ($commentLevel > 0)
{
$resultLine .= " ";
}
if ($explodedLine[$j] eq "/" && $explodedLine[($j+1)] eq "*")
{
$commentLevel++;
next;
}
if ($explodedLine[$j] eq "*" && $explodedLine[($j+1)] eq "/")
{
$commentLevel--;
$j++;
next;
}
if (($commentLevel == 0) || ($explodedLine[$j] eq "\n"))
{
$resultLine .= $explodedLine[$j];
}
}
$ARRAY[$i]=join(" ",$resultLine);
}
close(FH) or die "Closing: $!";