简体   繁体   English

Perl正则表达式匹配失败

[英]perl regex matching failed

I want to match two different string and output should come in $1 and $2, According to me in this example, if $a is 'xy abc', then $1 should be 'xy abc' and $2 should 'abc', but 'abc' part is coming in $3. 我想匹配两个不同的字符串,输出应该在$ 1和$ 2中,根据我在此示例中的说明,如果$ a是'xy abc',则$ 1应该是'xy abc'和$ 2应该是'abc',但是'abc部分将要支付3美元。 Can you please help me to writing a regex in that $1 should have whole string and $2 should have second part. 您能否帮我写一个正则表达式,因为$ 1应该有整个字符串,而$ 2应该有第二部分。 I am using perl 5.8.5. 我正在使用perl 5.8.5。

my @data=('abc xy','xy abc');
foreach my $a ( @data) {
    print "\nPattern= $a\n";
    if($a=~/(abc (xy)|xy (abc))/) {
        print "\nMatch: \$1>$1< \$2>$2< \$3>$3<\n";
    }
}

Output: 输出:

perl test_reg.pl

Pattern= abc xy

Match: $1>abc xy< $2>xy< $3><

Pattern= xy abc

Match: $1>xy abc< $2>< $3>abc<

Can be done with: 可以使用:

(?|(abc (xy))|(xy (abc)))

Why even bother with capturing the whole thing? 为什么还要费心去抓整个东西呢? You can use $& for that. 您可以为此使用$&

my @data = ('abc xy', 'xy abc');
for(@data) {
    print "String: '$_'\n";

    if(/(?|abc (xy)|xy (abc))/) {
        print "Match: \$&='$&', \$1='$1'\n";
    }
}

Because only one of captures $2 and $3 can be defined, you can write 因为只能定义捕获$2$3中的一个,所以您可以编写

foreach my $item ( @data) {

  print "\nPattern= $item\n";

  if ($item=~/(abc (xy)|xy (abc))/) {
    printf "Match: whole>%s< part>%s<\n", $1, $2 || $3;
  }
}

which gives the output 这给出了输出

Pattern= abc xy
Match: whole>abc xy< part>xy<

Pattern= xy abc
Match: whole>xy abc< part>abc<

If you can live with allowing more capture variables than $1 and $2 , then use the substrings from the branch of the alternative that matched. 如果您可以允许使用比$1$2更多的捕获变量,请使用匹配的替代方法分支中的子字符串。

for ('abc xy', 'xy abc') {
  print "[$_]:\n";

  if (/(abc (xy))|(xy (abc))/) {
    print "  - match: ", defined $1 ? "1: [$1], 2: [$2]\n"
                                    : "1: [$3], 2: [$4]\n";
  }
  else {
    print "  - no match\n";
  }
}

Output: 输出:

[abc xy]:
  - match: 1: [abc xy], 2: [xy]
[xy abc]:
  - match: 1: [xy abc], 2: [abc]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM