gpt4 book ai didi

regex - 乐/Perl6 : How to restrict match method to capture group?

转载 作者:行者123 更新时间:2023-12-03 18:18:55 27 4
gpt4 key购买 nike

我试图将文件名中的三个字母与 1000Genomes 项目匹配,并且仅匹配来自 ethnicity_lists/PEL.txt 之类的字符串中的三个字母。我应该只得到 PEL .字符串的其余部分无关紧要。

my $p1-label = @populations[$p1-index].match(/^ethnicity_lists\/(<[A..Y]>)**3\.txt$/);

问题是 $p1-label包括捕获组之外的整个字符串。

我在 <[A..Y]> 周围加了括号强调我只想要那个组。

翻阅 https://docs.perl6.org/routine/match

我尝试尽可能具体以防止任何可能的错误,这就是我包含整个字符串的原因。

如果我进行 Perl5 风格的匹配:
if @populations[$p1-index] ~~ /^ethnicity_lists\/(<[A..Y]>)**3\.txt$/ {
put $0.join(''); # strange that this outputs an array instead of a string
}

我已经尝试了 match 的所有副词方法,但没有做必要的工作。

我如何限制 match方法只捕获正则表达式中的组?

最佳答案

match 方法返回一个 Match 对象,其中包含有关您的匹配的所有信息。如果你这样做:

my $p1-label = @populations[$p1-index].match(/^ethnicity_lists\/(<[A..Y]>)**3\.txt$/);
say $p1-label;

您会看到它包含 3 个标记为 0 的项目由于括号外提到的**3:
「ethnicity_lists/PEL.txt」
0 => 「P」
0 => 「E」
0 => 「L」

获取 Match 对象的 Str 表示可为您提供完整的匹配。但你也可以要求它是 [0]指数。
say  say $p1-label[0]'
[「P」 「E」 「L」]

让我们修复正则表达式以将量词放在括号中,看看我们得到了什么。
my $p1-label = @populations[$p1-index].match(/^ethnicity_lists\/(<[A..Y]>**3)\.txt$/);
say $p1-label;
「ethnicity_lists/PEL.txt」
0 => 「PEL」

看起来更好。现在,如果您只想要 PEL你有两个选择。您可以获取匹配中第一项的 Str 表示:
my $p1-label = @populations[$p1-index].match(/^ethnicity_lists\/(<[A..Y]>**3)\.txt$/)[0].Str;
say $p1-label;
PEL

请注意,如果我不将其强制为字符串,我将获得子匹配的匹配对象。 (这可能有用,但不是您需要的)。

或者您可以使用零宽度断言并完全跳过捕获:
my $p1-label = @populations[$p1-index].match(/<?after ^ethnicity_lists\/><[A..Y]>**3<?before \.txt$>/).Str;
say $p1-label;
PEL

这里我们匹配出现在表达式 ^ethnicity_lists\/ 之后的 3 个大写字母及之前 \.txt$但他们不包括在比赛本身中。

或者正如@raiph 所指出的,您可以使用双重捕获来告诉系统这是您唯一想要的:
my $p1-label = @populations[$p1-index].match(/^ethnicity_lists\/<(<[A..Y]>**3)>\.txt$/)[0].Str;
say $p1-label;
PEL

这最后一个可能是最好的。

希望有帮助。

关于regex - 乐/Perl6 : How to restrict match method to capture group?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59308692/

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