首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

是否有Perl相当于Python的re.findall/re.finditer(迭代正则表达式结果)?

是的,Perl语言中也有类似Python的re.findall/re.finditer功能。在Perl中,可以使用正则表达式的=~操作符来进行匹配,并使用@+@-变量来获取匹配结果。

例如,在Python中,可以使用以下代码来获取匹配结果:

代码语言:python
复制
import re

text = "The quick brown fox jumps over the lazy dog"
pattern = r'\b\w+\b'

matches = re.findall(pattern, text)
print(matches)

在Perl中,可以使用以下代码来获取匹配结果:

代码语言:perl
复制
my $text = "The quick brown fox jumps over the lazy dog";
my $pattern = '\b\w+\b';

my @matches = $text =~ /$pattern/g;
print join(", ", @matches), "\n";

这两个代码段都会输出相同的结果:The, quick, brown, fox, jumps, over, the, lazy, dog

在Perl中,=~操作符会将匹配结果存储在@+@-变量中。@+变量包含了最后一次匹配的位置,而@-变量包含了最后一次匹配的长度。可以使用这些变量来获取匹配结果的位置和长度。

例如,在Perl中,可以使用以下代码来获取匹配结果的位置和长度:

代码语言:perl
复制
my $text = "The quick brown fox jumps over the lazy dog";
my $pattern = '\b\w+\b';

my @matches = $text =~ /$pattern/g;

for my $i (0..$#matches) {
    my $start = $+[$i];
    my $end = $+[$i+1];
    my $length = $end - $start;
    print "Match '$matches[$i]' starts at position $start and has length $length\n";
}

这个代码段会输出以下结果:

代码语言:txt
复制
Match 'The' starts at position 0 and has length 3
Match 'quick' starts at position 4 and has length 5
Match 'brown' starts at position 10 and has length 5
Match 'fox' starts at position 16 and has length 3
Match 'jumps' starts at position 20 and has length 5
Match 'over' starts at position 26 and has length 4
Match 'the' starts at position 31 and has length 3
Match 'lazy' starts at position 35 and has length 4
Match 'dog' starts at position 40 and has length 3

总之,Perl语言中也有类似Python的re.findall/re.finditer功能,可以使用=~操作符和@+@-变量来获取匹配结果。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的视频

领券