__DATA__
/*This is the file which is used for the
developing the code for multiple IO operation
Author : Hello Wolrd remove */
void main();
/*Hello World */
/* hello
world
good
morning
comment /*
/* Hello Good Morning
!!!!!!!!!!!!!!!!!*/
void main()
{
printf("Hello World");
}
上面的代码是我的c文件。在这里,我必须用“嗨”替换“你好”.. 如果我做简单解析文件并替换...它将在所有地方替换,对于代码的注释和非注释部分。但我必须在非评论部分替换它。是否可以替换?
在我阅读并重写相同的文件后,我应该有以下输出
__DATA__
/*This is the file which is used for the
developing the code for multiple IO operation
Author : Hello Wolrd remove */
/*Hello World */
/* hello
world
good
morning
comment /*
/* Hello Good Morning
!!!!!!!!!!!!!!!!!*/
void main()
{
printf("Hi World");
}
如何确定字符串是c文件的注释或非注释代码? 是否可以仅替换代码中的非注释部分?
答案 0 :(得分:2)
样品:
while (<>) {
s/($RE{comment}{C})//;
}
同时检查perlfaq:How do I use a regular expression to strip C-style comments from a file?
答案 1 :(得分:0)
扩展了使用Regexp::Common
的建议,以下使用comment
和quoted
模式执行此替换:
use strict;
use warnings;
use Regexp::Common;
my $data = do {local $/; <DATA>};
$data =~ s{$RE{comment}{C}\K|($RE{quoted})}{
my $string = $1 // '';
$string =~ s/Hello/Hi/g;
$string;
}eg;
print $data;
__DATA__
/*This is the file which is used for the
developing the code for multiple IO operation
Author : Hello Wolrd remove */
void main();
/*Hello World */
/* hello
world
good
morning
comment /*
/* Hello Good Morning
!!!!!!!!!!!!!!!!!*/
void main()
{
printf("Hello World");
}
输出:
/*This is the file which is used for the
developing the code for multiple IO operation
Author : Hello Wolrd remove */
void main();
/*Hello World */
/* hello
world
good
morning
comment /*
/* Hello Good Morning
!!!!!!!!!!!!!!!!!*/
void main()
{
printf("Hi World");
}