加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式 – 使用Perl验证年份范围

发布时间:2020-12-14 05:57:18 所属栏目:百科 来源:网络整理
导读:这些是源文件标题中的有效年份,版权行: 20162007,20162007-2010,20162010,2012-2016 本年度(2016年)应该是其中的一部分. 无效: 2016,2007 # not in order2010-2007,2016 #range not in order.2010-2015 # current year missing. 我制作了如下脚本,仍然在努
这些是源文件标题中的有效年份,版权行:

2016
2007,2016
2007-2010,2016
2010,2012-2016

本年度(2016年)应该是其中的一部分.

无效:

2016,2007 # not in order
2010-2007,2016 #range not in order.
2010-2015 # current year missing.

我制作了如下脚本,仍然在努力,是否有更好的方法来检查相同的?

use strict;
use warnings;
use List::Util 'first';
use Time::Piece;

my $t = Time::Piece->new();
my $currentYear=$t->year;

my $filename="sample.txt"; # this file name will be passed-in to the script.
my $fileContent=`cat $filename`;
my $copyrightFound = first { /copyright .* Shakespeare/i } $fileContent;
if (!$copyrightFound) {
     print "nERROR: Copyright missingn";
     exit;
}
#copyright Found
print $fileContent;
if ($fileContent =~ /Copyright (c) (.*) by Bill Shakespeares+.*All rights reserved./) {
    print "nCopyright is good: $1n";
    my $years = $1;
    print "n$years,$currentYearn";
    #e.g: 2016
    if ($years !~ ',' && $years !~ '-') {
       print "nerrorn" if ($years !~ /$currentYear/);
    }
    #e.g: 2010-2016
    elsif ($years !~ ',') {
       print "nErrorn" if ($years !~ /-$currentYear$/);
    }
    #eg: 2010,2016
    elsif ($years !~ '-') {
       print "nErrorn" if ($years !~ /,$currentYear$/);
    }
    #e.g: 2008,2010,2011-2016
    elsif ($years =~ '-' && $years =~ ',') {
       print "nError 5n" if ($years !~ /dddd,dddd-$currentYear$/);
    }
    else {
       print "invalid format"
    }

} else {
      print "nCopyright needs to be fixedn";
}

sample.txt有:

Copyright (c) 2008,2011-2016 by Bill Shakespeare
All rights reserved.

解决方法

您可以使用 Set::IntSpan来验证日期:

use warnings;
use strict;
use Set::IntSpan qw();

my $currentYear = 2016;

while (<DATA>) {
    s/s+//g;
    my $ok = 0;
    if (Set::IntSpan->valid($_)) { # Checks order
        my $set = Set::IntSpan->new($_);
        my @years = $set->elements();
        $ok = 1 if grep { $_ == $currentYear } @years;
    }
    print "$ok : $_n";
}

__DATA__
2007
2007,2012-2016
2016,2007
2010-2007,2016
2010-2015

这打印:

0 : 2007
1 : 2007,2016
1 : 2007-2010,2016
1 : 2010,2012-2016
0 : 2016,2007
0 : 2010-2007,2016
0 : 2010-2015

正如pilcrow在评论中所建议的那样,简化使用成员而不是grep:

my $ok = 0;
if (Set::IntSpan->valid($_)) { 
    my $set = Set::IntSpan->new($_);
    $ok = 1 if $set->member($currentYear);
}
print "$ok : $_n";

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读