gpt4 book ai didi

perl - 为什么正面前瞻会导致在我的 Perl 正则表达式中进行捕获?

转载 作者:行者123 更新时间:2023-12-02 07:14:07 24 4
gpt4 key购买 nike

我不明白为什么这段代码有效:

$seq = 'GAGAGAGA';
my $regexp = '(?=((G[UCGA][GA]A)|(U[GA]CG)|(CUUG)))'; # zero width match
while ($seq =~ /$regexp/g){ # globally
my $pos = pos($seq) + 1; # position of a zero width matching
print "$1 position $pos\n";
}

我知道这是一个零宽度匹配,它不会将匹配的字符串放在 $& 中,但为什么将它放在 $1 中?

谢谢!

最佳答案

由于所有内部括号,匹配项被捕获在 $1 中。如果您不想捕获,请使用

my $regexp = '(?=(?:(?:G[UCGA][GA]A)|(?:U[GA]CG)|(?:CUUG)))';

甚至更好

my $regexp = qr/(?=(?:(?:G[UCGA][GA]A)|(?:U[GA]CG)|(?:CUUG)))/;

来自perlre documentation :

  • (?:pattern)
  • (?imsx-imsx:pattern)

This is for clustering, not capturing; it groups subexpressions like (), but doesn't make backreferences as () does. So

@fields = split(/\b(?:a|b|c)\b/)

is like

@fields = split(/\b(a|b|c)\b/)

but doesn't spit out extra fields. It's also cheaper not to capture characters if you don't need to.

Any letters between ? and : act as flags modifiers as with (?imsx-imsx). For example,

/(?s-i:more.*than).*million/i

is equivalent to the more verbose

/(?:(?s-i)more.*than).*million/i

关于perl - 为什么正面前瞻会导致在我的 Perl 正则表达式中进行捕获?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2529002/

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