1

我想用 "xx:xx:xx" 替换 Perl 中 2 个字符串的 "hh:mm:ss" 的 reg 表达式我该怎么做?

代码:

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";
}
4

2 回答 2

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;
于 2012-07-05T20:48:56.243 回答
2

toolic 的解决方案有效,但如果您想使用带有默认变量的替换命令$_,请使用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";
}
于 2012-07-05T20:54:21.687 回答