是的,Perl语言中也有类似Python的re.findall/re.finditer功能。在Perl中,可以使用正则表达式的=~
操作符来进行匹配,并使用@+
和@-
变量来获取匹配结果。
例如,在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中,可以使用以下代码来获取匹配结果:
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中,可以使用以下代码来获取匹配结果的位置和长度:
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";
}
这个代码段会输出以下结果:
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功能,可以使用=~
操作符和@+
、@-
变量来获取匹配结果。
领取专属 10元无门槛券
手把手带您无忧上云