I 目前需要正则表达式来搜索和替换所有 |–|与|-|。我目前正在更换 |`|与 |'|它正在使用:
while($_ =~ s/`/'/g)
{
print "Line: '$.'. ";
print "Found '$&'. ";
}
但是,使用相同的正则表达式并不适用于我的以下所有尝试:
while($_ =~ s/\–/-/g)
{
print "Line: '$.'. ";
print "Found '$&'.\n";
}
while($_ =~ s/\–/-/g)
{
print "Line: '$.'. ";
print "Found '$&'.\n";
}
while($_ =~ s/\&ndash/-/g)
{
print "Line: '$.'. ";
print "Found '$&'.\n";
}
while($_ =~ s/\–/-/g)
{
print "Line: '$.'. ";
print "Found '$&'.\n";
}
while($_ =~ s/–/-/g)
{
print "Line: '$.'. ";
print "Found '$&'.\n";
}
while($_ =~ s/&ndash/-/g)
{
print "Line: '$.'. ";
print "Found '$&'.\n";
}
脚本当前如下所示:
#!/usr/bin/perl
use strict;
use warnings;
my $FILE;
my $filename = 'NoDodge.c';
open($FILE,"<service.c") or die "File not opened";
open(my $fh, '>', $filename) or die "Could not open file '$filename' $!";
while (<$FILE>)
{
while($_ =~ s/`/'/g)
{
print "Line: '$.'. ";
print "Found '$&'. ";
}
while($_ =~ s/\–/-/g)
{
print "Line: '$.'. ";
print "Found '$&'.\n";
}
print $fh $_;
}
close $fh;
print "\nCompleted\n";
当前结果示例:
行:“152”。找到“`”。
行:“162”。找到“`”。
已完成
解决方案: 由鲍罗丁提供,
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use open qw/ :std :encoding(utf8) /;
my $FILE;
my $fh;
my $readfile = 'service.c';
my $writefile = 'NoDodge.c';
open($FILE,'<',$readfile) or die qq{Unable to open "$readfile" for input: $!};
open($fh, '>',$writefile) or die qq{Unable to open "$writefile" for output: $!};
while (<$FILE>)
{
while(s/–/-/g)
{
print "Found: $& on Line: $.\n";
}
while(s/`/'/g)
{
print "Found: $& on Line: $.\n";
}
print $fh $_;
}
close $fh;
close $FILE;
print "\nService Migrated to $writefile\n";
示例输出:
发现:-在线:713
发现:` 线路:713
发现:-在线:724
发现:`在线:724
发现:`在线:794
服务迁移至NoDodge.c
最佳答案
您需要在程序顶部使用 utf8
,否则 Perl 将看到构成短划线 (E2
) 的 UTF-8 编码的各个字节> 80
93
)。也不需要指定 $_
作为替换的对象,因为它是默认的,并且您不需要转义短破折号,因为它不是正则表达式模式中的特殊字符
use utf8;
...
while( s/–/-/g ) { ... }
或者您可能希望使用 Unicode 名称使其更清晰,因为乍一看您要替换的内容并不明显。在这种情况下,您不需要使用 utf8
,只要您命名每个非 ASCII 字符而不是按字面意思使用它,就像这样
while( s/\N{EN DASH}/-/g ) { ... }
您还需要以 UTF-8 编码打开文件(输入和输出)。最简单的方法是将 UTF-8 设置为默认模式。您可以将此行添加到程序顶部附近
use open qw/ :std :encoding(utf8) /;
或者您可以像这样以 UTF-8 编码显式打开每个文件
my $filename = 'NoDodge.c';
open my $in_fh, '<:encoding(utf8)', 'service.c'
or die qq{Unable to open "service.c" for input: $!};
open my $out_fh, '>:encoding(utf8)', $filename
or die qq{Unable to open "$filename" for output: $!};
关于regex - 在 perl 中搜索和用普通破折号替换小数破折号的正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32582631/