perl regex场景

时间:2018-03-07 16:28:31

标签: regex perl perl-module

根据用户输入,即$ release_num,我必须对特定操作进行调用。

它在某些情况下工作但在其他一些情况下失败。需要帮助来完善最终解决方案。

代码:

my $release_num;

my $short_release_num = substr($release_num, 0, 4);

if (($short_release_num eq '20a0') or ($short_release_num eq '20a1') or ($short_release_num eq '20a2'))
{
    print " Build is required \n";
}
else
{
    print " Build is NOT required \n";
}

用户输入$ release_num的可能值如下:

$release_num = "20a1";
$release_num = "20a1a11";
$release_num = "20a10";
$release_num = "20a10a11";
$release_num = "20a11";
$release_num = "20a11a1";

虽然我的代码适用于某些特定情况(20a1),但它不是通用解决方案,因为它在20a10a11等情况下失败了。请建议如何改进代码。

例如:如果输入为20a10或20a10a11,则输出应为"Build is NOT required",而输出为“Build is required”。

预期结果:

对于以下输入,我们应该得到“Build is required”:

$release_num = "20a0";
$release_num = "20a0a1";
$release_num = "20a1";
$release_num = "20a1a2";
$release_num = "20a2a11";
$release_num = "20a2a1";

对于以下输入,我们应该得到“不需要构建”:

$release_num = "20a10";
$release_num = "20a10a11";
$release_num = "20a11";
$release_num = "20a11a1";

2 个答案:

答案 0 :(得分:1)

根据给定的情况,我猜期望的答案更像是

if ( $release_num =~ /^20a[012](?!\d)/ ) {
    print " Build is required \n";
}
else {
    print " Build is NOT required \n";
}

答案 1 :(得分:0)

示例输入是好的,如果你能另外解释何时需要"构建的规则,那就更好了。当它不是时。基于您的(可能不完整的!)示例输入:

use warnings;
use strict;
use Test::More;

my $build_is_required_regex = qr/^20a\d(?!\d)/;

like   "20a0",     $build_is_required_regex;
like   "20a0a1",   $build_is_required_regex;
like   "20a1",     $build_is_required_regex;
like   "20a1a2",   $build_is_required_regex;
like   "20a2a11",  $build_is_required_regex;
like   "20a2a1",   $build_is_required_regex;
unlike "20a10",    $build_is_required_regex;
unlike "20a10a11", $build_is_required_regex;
unlike "20a11",    $build_is_required_regex;
unlike "20a11a1",  $build_is_required_regex;

done_testing;

这意味着:

if ( $release_num =~ /^20a\d(?!\d)/ ) {
    print " Build is required \n";
}
else {
    print " Build is NOT required \n";
}