如何在Perl中找到与正则表达式的所有匹配项? [英] How can I find all matches to a regular expression in Perl?

查看:296
本文介绍了如何在Perl中找到与正则表达式的所有匹配项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下形式的文本:

Name=Value1
Name=Value2
Name=Value3

使用Perl,我想在/Name=(.+?)/每次出现时都进行匹配,并提取(.+?)并将其推入数组.我知道我可以使用$1来获取所需的文本,也可以使用=~来进行正则表达式匹配,但是我不知道如何获取所有匹配项.

Using Perl, I would like to match /Name=(.+?)/ every time it appears and extract the (.+?) and push it onto an array. I know I can use $1 to get the text I need and I can use =~ to perform the regex matching, but I don't know how to get all matches.

推荐答案

列表上下文中的m//g返回所有捕获的匹配项.

A m//g in list context returns all the captured matches.

#!/usr/bin/perl

use strict; use warnings;

my $str = <<EO_STR;
Name=Value1
Name=Value2
Name=Value3
EO_STR

my @matches = $str =~ /=(\w+)/g;
# or my @matches = $str =~ /=([^\n]+)/g;
# or my @matches = $str =~ /=(.+)$/mg;
# depending on what you want to capture

print "@matches\n";

但是,您似乎正在解析INI样式的配置文件.在这种情况下,我会推荐 Config :: Std .

However, it looks like you are parsing an INI style configuration file. In that case, I will recommend Config::Std.

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

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