Perl:如何从 "d days, h:mm:ss" 中提取

Perl: how to extract from "d days, h:mm:ss"

我希望用这种格式的设备正常运行时间做数学计算 "d days, h:mm:ss"(或者 "h:mm:ss" 如果设备不超过一天但我可以编程如何检查)

我的问题是如何从字符串中提取 dhmmss 这样我就可以用它进行计算(使用 DateTime我也在这里找到了)

这可以通过带有一些捕获组的简单正则表达式来解决。

这需要一个格式为 "d days, h:mm:ss" 的时间,并会给出天、时、分和秒。

#!/usr/bin/perl
use strict;
use warnings;

# Define a random time
my $time = '4 days, 03:44:23';

# Extract the data from the time
my ($days, $h, $m, $s) = $time =~ m/([0-9]+)\sdays,\s([0-9]+):([0-9]+):([0-9]+)/;

# Print the output
print 'time: '.$time."\n\n";
print 'days: '.$days."\n";
print 'h   : '.$h."\n";
print 'm   : '.$m."\n";
print 's   : '.$s."\n";

有关如何使用正则表达式的更多信息可能对您有所帮助:perlre (regular expression tutorial)

此外,由于您是 Perl 的新手,我将补充一点,您应该 始终 在代码顶部添加 use strict;use warnings;。它会阻止您犯愚蠢的错误(例如尝试使用未定义的变量)并为您省去很多麻烦。


您还可以通过将匹配放在 if 语句中来验证您是否拥有正确的数据。养成这样做的习惯很好。

my ($days, $h, $m, $s);
if ($time =~ m/([0-9]+)\sdays,\s([0-9]+):([0-9]+):([0-9]+)/) {
    ($days, $h, $m, $s) = (, , , )
}
else {
    die "Invalid date format encountered!";
}

由于这看起来像是一个可教授的时刻,我将添加 tjwrona1992 的正则表达式

my ($days, $h, $m, $s) = $time =~ m/([0-9]+)\sdays,\s([0-9]+):([0-9]+):([0-9]+)/;

可以使用 /x 修饰符编写以允许空格和注释,使其更易于人类消费者理解:

    my ($days, $h, $m, $s) = $time =~ m/
              ([0-9]+) \s days, #  will be days
              \s
              ([0-9]+) :        #  = hours     
              ([0-9]+) :        #  = minutes
              ([0-9]+)          #  = seconds

        /x or die "the regex did not match '$time'";