【问题标题】:Perl conditional regex extractionPerl条件正则表达式提取
【发布时间】:2014-02-19 06:46:02
【问题描述】:

此条件必须匹配 telco_imac_city 或 telco_hier_city。当它成功时,我需要提取匹配值的第二个下划线。

我可以用这段代码让它工作

if ( ($value =~ /(telco_imac_)city/) || ($value =~ /(telco_hier_)city/) ) {
    print "value is: \"$1\"\n";
}

但如果可能的话,我宁愿使用这样的单个正则表达式

$value = $ARGV[0];
if ( $value =~ /(telco_imac_)city|(telco_hier_)city/ ) {
    print "value is: \"$1\"\n";
}

但如果我传递值 telco_hier_city 我会在测试第二个值时得到这个输出

Use of uninitialized value $1 in concatenation (.) or string at ./test.pl line 19.
value is: ""

我做错了什么?

【问题讨论】:

    标签: regex perl


    【解决方案1】:
    while (<$input>){
        chomp;
        print "$1\n" if /(telco_hier|telco_imac)_city/;
    }
    

    【讨论】:

    • OP 希望返回“只返回匹配值的第二个下划线”(即telco_hier_ 或telco_imac_)。
    【解决方案2】:

    Perl capture groups 根据单个语句中的匹配进行编号。您的输入 telco_hier_city 与该单个正则表达式 (/(telco_imac_)city|(telco_hier_)city/) 的 second 捕获相匹配,这意味着您需要使用 $2:

    my $value = $ARGV[0];
    if ( $value =~ /(telco_imac_)city|(telco_hier_)city/ ) {
        print "value is: \"$2\"\n";
    }
    

    输出:

    $> ./conditionalIfRegex.pl telco_hier_city
    value is: "telco_hier_"
    

    因为在您的第一个捕获组 ((telco_imac_)) 中没有匹配项,$1 未初始化,正如预期的那样。

    要修复您的原始代码,请使用FlyingFrog's regex:

    my $value = $ARGV[0];
    if ( $value =~ /(telco_hier_|telco_imac_)city/ ) {
        print "value is: \"$1\"\n";
    }
    

    输出:

    $> ./conditionalIfRegex.pl telco_hier_city
    value is: "telco_hier_"
    
    $> ./conditionalIfRegex.pl telco_imac_city
    value is: "telco_imac_"
    

    【讨论】:

    • 当$value 是telco_imac_ 时会发生什么?
    • @FlyingFrog 使用您的正则表达式进行编辑(稍作修改的版本),谢谢!答案的原始部分有助于 OP 理解为什么会发生未初始化的警告。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-24
    • 2015-01-19
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多