替换2 Perl中的非默认行正则表达式

时间:2012-07-05 20:38:49

标签: regex perl syntax substitution

我想将Perl中2个字符串的“hh:mm:ss”的reg表达式替换为“xx:xx:xx”我该如何实现?

代码:

use strict;
use warnings;
my $l="12:48:25 - Properties - submitMode : 2";
my $r="54:01:00 - Properties - submitMode : 2";
#my $newLn;
#Find "hh:mm:ss" in $_ :P
if ($l =~ /\d\d:\d\d:\d\d/ || $r=~ /\d\d:\d\d:\d\d/) {
#print "Time found";
s/\d\d:\d\d:\d\d/xx:xx:xx/g; #looking for default $_ , but have $l and $r
s/\d\d:\d\d:\d\d/xx:xx:xx/g;    
     #substitute with xx: p
print $l,"\n";
print $r,"\n";
} else {
print "No time found found";
}

2 个答案:

答案 0 :(得分:2)

$l =~ s/\d\d:\d\d:\d\d/xx:xx:xx/g;
$r =~ s/\d\d:\d\d:\d\d/xx:xx:xx/g;

答案 1 :(得分:2)

toolic的解决方案有效,但如果您想将substitute命令与默认变量$_一起使用,请使用foreach循环,如下所示:

use strict;
use warnings;
my $l="12:04:25 - Properties - submitMode : 2";
my $r="54:01:00 - Properties - submitMode : 2";
#my $newLn;
#Find "hh:mm:ss" in $_ :P
#if ($l =~ /\d\d:\d\d:\d\d/ || $r=~ /\d\d:\d\d:\d\d/) {

for ( $l, $r ) { 
    s/\d\d:\d\d:\d\d/xx:xx:xx/g || 
        do { 
            print "Not time found in $_\n"; 
            next 
        };
    print $_,"\n";
}