【问题标题】:Using multiple backreference in Perl在 Perl 中使用多重反向引用
【发布时间】:2019-05-05 21:50:56
【问题描述】:

我正在尝试在 Perl 中使用多个反向引用来匹配 5 种不同的模式,但除了第一个之外我没有得到任何匹配。

我尝试了以下方法:

my $string = ">abc|XYUXYU|KIOKEIK_7XNCU Happy, not-happy apple banana X ORIG=Came from trees NBMR 12345 OZ=1213379 NG=popZ AZ=2 BU=1";
$string =~ m/>(abc)|(.*)|.*ORIG=(.*)[A-Z].*NG=(.*)\s(.*)\s/;

print "First match should be 'abc'. We got: $1\n";
print "Second match should be 'XYUXYU'. We got: $2\n";
print "Third match should be 'Came from trees'. We got: $3\n";
print "Fourth match should be 'popZ'. We got: $4\n";
print "Fifth match should be 'AZ=2'. We got: $5\n";

我想作为输出:

First match should be 'abc'. We got: abc
Second match should be 'XYUXYU'. We got: XYUXYU
Third match should be 'Came from trees'. We got: Came from trees
Fourth match should be 'popZ'. We got: popZ
Fifth match should be 'AZ=2'. We got: AZ=2

任何线索如何在 Perl 上以正确的方式解决这个问题?

【问题讨论】:

  • 语言名称是 Perl,而不是 PERL。这不是首字母缩写词

标签: regex perl backreference


【解决方案1】:

您必须通过在 \ 前面加上 | 来转义它们,否则它们意味着交替(a|b 匹配 ab)。对于您的第三场比赛,您必须通过附加? 使量词* 非贪婪。并且您需要稍微调整第三个捕获组之后的模式以匹配至少一个大写字符的空格(这里并不完全清楚整体可能性是什么,因为您只是给出了一个没有进一步细节的示例。它可能需要进一步调整.)

#!/usr/bin/perl

use strict;
use warnings;

my $string = ">abc|XYUXYU|KIOKEIK_7XNCU Happy, not-happy apple banana X ORIG=Came from trees NBMR 12345 OZ=1213379 NG=popZ AZ=2 BU=1";
$string =~ m/>(abc)\|(.*)\|.*ORIG=(.*?)\s[A-Z]+.*NG=(.*)\s(.*)\s/;

print "First match should be 'abc'. We got: $1\n";
print "Second match should be 'XYUXYU'. We got: $2\n";
print "Third match should be 'Came from trees'. We got: $3\n";
print "Fourth match should be 'popZ'. We got: $4\n";
print "Fifth match should be 'AZ=2'. We got: $5\n";

输出:

First match should be 'abc'. We got: abc
Second match should be 'XYUXYU'. We got: XYUXYU
Third match should be 'Came from trees'. We got: Came from trees
Fourth match should be 'popZ'. We got: popZ
Fifth match should be 'AZ=2'. We got: AZ=2

【讨论】:

  • 我给出了这个案例,它是从多个文本文件中的类似模式修改而来的。它适用于您的答案。谢谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-12
  • 1970-01-01
  • 1970-01-01
  • 2017-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多