使用 Perl 多次匹配正则表达式 [英] Matching a regular expression multiple times with Perl

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

问题描述

菜鸟问题在这里.我有一个非常简单的 perl 脚本,我希望正则表达式匹配字符串中的多个部分

Noob question here. I have a very simple perl script and I want the regex to match multiple parts in the string

my $string = "ohai there. ohai";
my @results = $string =~ /(\w\w\w\w)/;
foreach my $x (@results){
    print "$x\n";
}

这不是我想要的方式,因为它只返回 ohai.我希望它匹配并打印出ohai ther ohai

This isn't working the way i want as it only returns ohai. I would like it to match and print out ohai ther ohai

我该怎么做.

谢谢

推荐答案

这会满足您的需求吗?

my $string = "ohai there. ohai";
while ($string =~ m/(\w\w\w\w)/g) {
    print "$1\n";
}

它回来了

ohai
ther
ohai

来自 perlretut:

From perlretut:

修饰符//g"代表全局匹配并允许匹配运算符以匹配一个字符串尽可能多.

The modifier "//g" stands for global matching and allows the matching operator to match within a string as many times as possible.

此外,如果您想将匹配项放入数组中,您可以这样做:

Also, if you want to put the matches in an array instead you can do:

my $string = "ohai there. ohai";
my @matches = ($string =~ m/(\w\w\w\w)/g);
foreach my $x (@matches) {
    print "$x\n";
}    

这篇关于使用 Perl 多次匹配正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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