简体   繁体   English

perl-如何找到模式的所有巧合

[英]perl - how to find all coincidences to pattern

For example I have a string "babdbeb" and pattern "bb". 例如,我有一个字符串“ babdbeb”和模式“ bb”。 I want to find following substrings here: 我想在这里找到以下子字符串:

bab
bdb
beb

What is the best way of doing this? 最好的方法是什么?

PS I'm very new to Perl programming. PS我对Perl编程很陌生。

You can use a lookahead pattern, see perlre 您可以使用先行模式,请参见perlre

while ("babdbeb" =~ m/b(?=(.b))/g) {
        print "b$1\n";
}

This yields a match without the leading b , but allows to restart the search and find intermediate bb s 这将产生一个不带前导b的匹配项,但允许重新开始搜索并找到中间的bb s

my $s = "babdbeb";
while ($s =~ /(b.b)/g) {
  print "$1\n";
  # decrease position where search left of by 2 (3 is length of 'b.b' -1)
  # pos() is lvalue function http://perldoc.perl.org/functions/pos.html
  pos($s) -= (length($1) -1);
}

output 输出

bab
bdb
beb

You can use overlapping regex matching using positive lookahead assertion. 您可以使用正向超前断言使用重叠的正则表达式匹配。 Here is an example: 这是一个例子:

$\ = $/; ## adding \n after every print.

my $string = "babdbeb";
print for $string =~ /(?=(b.b))/g;

Output: 输出:

bab
bdb
beb

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM