gpt4 book ai didi

regex - 使用 Perl 多次匹配正则表达式

转载 作者:行者123 更新时间:2023-12-04 02:42:38 25 4
gpt4 key购买 nike

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

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

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

我将如何去做这件事。

谢谢

最佳答案

这会做你想要的吗?

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

它返回
ohai
ther
ohai

来自 perlretut:

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



此外,如果您想将匹配项放入数组中,您可以执行以下操作:
my $string = "ohai there. ohai";
my @matches = ($string =~ m/(\w\w\w\w)/g);
foreach my $x (@matches) {
print "$x\n";
}

关于regex - 使用 Perl 多次匹配正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6374783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com