从同一个 Perl 正则表达式中捕获多个匹配项? [英] Capture multiple matches from the same Perl regex?

查看:54
本文介绍了从同一个 Perl 正则表达式中捕获多个匹配项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a file containing text:

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?

我试过了:

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

请提出建议.

推荐答案

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

If you want to capture mayank followed by a number, you can use the following regex :

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

如果数字是必填的,请将其更改为/(mayank\d+)/.

If the number is mandatory, change it to /(mayank\d+)/.

简短说明 : \d 匹配单个数字,所以 \d* 匹配尽可能多的数字(如果有,则为零none),并且 \d+ 匹配尽可能多的数字(但至少有一个).

Short explanation : \d matches a single digit, so \d* matches as many digits as possible (or zero if there is none), and \d+ matches as many digit as possible (but at least one).

为什么您的解决方案不起作用:

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

/(mayank.*?)/ uses a non-greedy quantifier (*?), which try to match at little characters as possible, so nothing.
/(mayank.?)/ will capture whatever character comes after mayank (even a space), if there is one.

这篇关于从同一个 Perl 正则表达式中捕获多个匹配项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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