Perl:匹配时为空的$ 1正则表达式值吗? [英] Perl: Empty $1 regex value when matching?

查看:153
本文介绍了Perl:匹配时为空的$ 1正则表达式值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

读者,

我遇到以下正则表达式问题:

I have the following regex problem:

代码

 #!/usr/bin/perl -w
use 5.010;
use warnings;

my $filename = 'input.txt';
open my $FILE, "<", $filename or die $!;

while (my $row = <$FILE>)
{                   # take one input line at a time
    chomp $row;
    if ($row =~ /\b\w*a\b/)
    {
       print "Matched: |$`<$&>$'|\n";  # the special match vars
       print "\$1 contains '$1' \n";
    }
    else
    {
       #print "No match: |$row|\n";
    }
}

input.txt

I like wilma. 
this line does not match

输出

Matched: |I like <wilma>|
Use of uninitialized value $1 in concatenation (.) or string at ./derp.pl line 14, <$FILE> line 22.
$1 contains ''

我完全感到困惑.如果匹配,并且我在有条件的情况下检查事物.为什么我得到1美元的空结果?这不应该发生.我究竟做错了什么?如何获得'wilma'在$ 1中?

I am totally confused. If it is matching and I am checking things in a conditional. Why am I getting an empty result for $1? This isn't supposed to be happening. What am I doing wrong? How can I get 'wilma' to be in $1?

我在此处进行了查找,但这没有帮助,因为我正在获得匹配".

I looked here but this didn't help because I am getting a "match".

推荐答案

您的正则表达式中没有任何括号.没有括号,没有$ 1.

You don't have any parentheses in your regex. No parentheses, no $1.

我猜您要以-a结尾的"word"值,所以应该是/\b(\w*a)\b/.

I'm guessing you want the "word" value that ends in -a, so that would be /\b(\w*a)\b/.

或者,由于您的整个正则表达式仅匹配您想要的位,因此您可以像在调试输出中一样使用$&代替$1.

Alternatively, since your whole regex only matches the bit you want, you can just use $& instead of $1, like you did in your debug output.

另一个例子:

my $row = 'I like wilma.';
$row =~ /\b(\w+)\b\s*\b(\w+)\b\s*(\w+)\b/;
print join "\n", "\$&='$&'", "\$1='$1'", "\$2='$2'", "\$3='$3'\n";

上面的代码产生以下输出:

The above code produces this output:

$&='I like wilma'
$1='I'
$2='like'
$3='wilma'

这篇关于Perl:匹配时为空的$ 1正则表达式值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆