
[英]How can I match text and replace it with a computed value based on the match in Perl?
[英]How can I replace all the text before the match in a Perl substitution?
我正在读取输入文件(IN)的每一行并将行读取打印到输出文件(OUT),如果该行以其中一种模式开头,例如“ab”,“cd”,“ef”,“gh”打印的行是“pattern:100”形式或“pattern:100:200”形式。 我需要将“pattern”替换为“myPattern”,即将当前行打印到FILE,但在第一次出现“:”之前用“myPattern”替换所有文本。 做这个的最好方式是什么?
目前我有:
while ( <IN> )
{
print FILE if /^ab:|^bc:|^ef:|^gh:/;
}
我不确定substr替换是否有帮助,因为“pattern”可以是“ab”或“cd”或“ef”或“gh”等。
谢谢! 双
通常,这样做:
my %subst = ( 'ab' => 'newab', 'bc' => 'newbc', 'xy' => 'newxy' );
my $regex = join( '|', map quotemeta, sort { length($b) <=> length($a) } keys %subst );
$regex = qr/^($regex):/;
while ( <IN> ) {
print FILE if s/$regex/$subst{$1}:/;
}
排序首先放置最长的,因此如果数据具有ab ::并且ab和ab都被替换,则使用ab:而不是ab。
默认情况下Perl的替换运算符(a)使用第一个匹配,(b)仅替换一个匹配,(c)如果替换则返回true,否则返回false。
所以:
while ( <IN> )
{
if (s/<pattern1>:/<replace1>/ ||
s/<pattern2>:/<replace2>/) {
print FILE;
}
}
应该适合你。 请注意,由于短路,只会进行一次替换。
while ( <IN> )
{
s/^pattern:/myPattern:/;
print OUT
}
这可能是你想要的:
$expr = "^(ab)|(cd)|(ef)|(gh)|(ij)";
while (<IN>)
{
if (/$expr:/)
{
s/$expr/$myPattern/;
print FILE;
}
}
sub replacer {
$line = shift;
$find = shift;
$replace = shift;
$line =~ /([^:]+):/
if ($1 =~ /$find/) {
$line =~ s/([^:]+):/$replace/ ;
return $line;
}
return ;
}
while (<IN>)
{
print OUT replacer ($_,"mean","variance");
print OUT replacer ($_,"pattern","newPattern");
}
我的perl有点生疏,所以语法可能不准确。
编辑 :把它放在ya的函数中。
执行上述要求的最短路径是重用代码,但包含替换。
while ( <IN> )
{
print FILE if s/^(ab|bc|ef|gh):/MyPattern:/;
}
任何左侧图案都将被替换。 如果左侧不匹配,则不会打印任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.