从同一个Perl正则表达式中捕获多个匹配项?

时间:2016-09-11 12:09:21

标签: regex perl

我有一个包含文字的文件:

hello mayank1 kumar mayank21
yadav Kevin has at most 
K
K minutes to perform this operations. He decides mayank3 that the string is super mayank4
if it is the lexicographically 
smallest among all possible strings mayank15
that he can get. Your task is to help Kevin and 
find this mayank2 lexicographically mayank8 smallest string mayank9

如何找到所有mayank<number>

我试过了:

use strict;

open( FH, "testfile.txt" ) or die "Can't open file for reading.";
while ( my $line = <FH> ) {
    chomp($line);
    while ( $line =~ /(mayank.*?)/g ) {
        print "$1\n";
    }
}

给出了:

mayank
mayank
mayank
mayank
mayank
mayank
mayank
mayank

使用时:

while ($line =~ /(mayank.?)/g) {
    print "$1\n";
}

我得到了

mayank1
mayank2
mayank3
mayank4
mayank1
mayank2
mayank8
mayank9

请建议。

2 个答案:

答案 0 :(得分:5)

如果要捕获mayank后跟数字,可以使用以下正则表达式:

while ($line =~ /(mayank\d*)/g) {
    print "$1\n";
}

如果该号码是强制性的,请将其更改为/(mayank\d+)/

简短说明\d匹配单个数字,因此\d*匹配尽可能多的数字(如果没有,则为零),\d+匹配尽可能多的数字(但至少有一个)。

为什么您的解决方案无法运作

/(mayank.*?)/使用非贪婪量词(*?),尝试尽可能匹配小字符,所以没有。 /(mayank.?)/将捕获mayank之后的任何字符(即使是空格),如果有的话。{/ p>

答案 1 :(得分:0)

您想要捕获 mayank #id ,其中 id 是一个数字,或者什么都不是:

$line =~ /(mayank)(\d+)?/
  • $ 1 :将举行mayank
  • $ 2 :将保留 ID 或将为空(undef)

您可以在阅读手册时找到有关正则表达式的更多信息:

man perlre