在一串字母中找到特定的字母序列

finding certain letter sequences in a string of letters

我有一串字母,我需要找到某些字母序列 ex。 BAENNN(N 可以是字母表中的任何字母)或 BAEMOP 以及该字母序列结束的位置。所以输出应该是序列和它结束的位置。字母串中可以有多个字母序列,只是位置不同而已。

这是我目前拥有的:

#!/usr/bin/perl
use warnings;
use strict;
use diagnostics;

my $string = a long string of letters
if $string =~ m/regex/; {
    print the repeat and the position where that letter sequence ends. 

我需要输入什么正则表达式代码? 我认为会是

m/(BAE[A-Z][A-Z][A-Z] | BAEMOP)/;
   print  

然后与 pos() 函数有关。但我只得到一个值。

谢谢大家的帮助!!

if 只运行一次。如果你想匹配多次,你需要一个循环。此外,您需要添加 /g 修饰符以在上一场比赛结束的地方开始下一场比赛。

另请注意,BAEMOP 与 BAENNN 匹配,因此在正则表达式中不需要它。

你的想法是对的,但是语法不对。条件需要括号(除非在后缀修饰符中),正则表达式不会忽略 | 周围的空格,除非您使用 /x 修饰符。

#!/usr/bin/perl
use strict;
use warnings;
use feature qw{ say };

#                      1         2
#             12345678901234567890123456789
my $string = 'AAABBBCCCDDDEEEBAEZZZXBAEABCZ';

while ($string =~ /(BAE[A-Z]{3})/g) {
    say , ' at ', pos $string;
}

输出:

BAEZZZ at 21
BAEABC at 28

如果您要查找的序列可能重叠,您将需要环视 断言。有关详细信息,请参阅 perlre