gpt4 book ai didi

match - 为什么在 `<( )>`中多次使用 `comb` token 的行为不符合预期?

转载 作者:行者123 更新时间:2023-12-03 16:15:22 25 4
gpt4 key购买 nike

我想提取28_2820201112122420516_000000中的行键(这里是bcp_startSoc),列名(这里是64.0)和值(这里是$str),其中$str是HBase中的一行:

# `match` is OK
my $str = '28_2820201112122420516_000000 column=d:bcp_startSoc, timestamp=1605155065124, value=64.0';
my $match = $str.match(/^ ([\d+]+ % '_') \s 'column=d:' (\w+) ',' \s timestamp '=' \d+ ',' \s 'value=' (<-[=]>+) $/);
my @match-result = $match».Str.Slip;
say @match-result; # Output: [28_2820201112122420516_000000 bcp_startSoc 64.0]

# `smartmatch` is OK
# $str ~~ /^ ([\d+]+ % '_') \s 'column=d:' (\w+) ',' \s timestamp '=' \d+ ',' \s 'value=' (<-[=]>+) $/
# say $/».Str.Array; # Output: [28_2820201112122420516_000000 bcp_startSoc 64.0]

# `comb` is NOT OK
# A <( token indicates the start of the match's overall capture, while the corresponding )> token indicates its endpoint.
# The <( is similar to other languages \K to discard any matches found before the \K.
my @comb-result = $str.comb(/<( [\d+]+ % '_' )> \s 'column=d:' <(\w+)> ',' \s timestamp '=' \d+ ',' \s 'value=' <(<-[=]>+)>/);
say @comb-result; # Expect: [28_2820201112122420516_000000 bcp_startSoc 64.0], but got [64.0]
我希望 comb跳过一些匹配项,只匹配我想要的匹配项,因此我在这里使用了多个 <()>,但只得到了最后一个匹配项。
是否可以使用 comb获得与oj​​it_code方法相同的结果?

最佳答案

TL; DR 多个<(...)>并不意味着多次捕获。即使它们这样做,.comb也会将每个匹配项减少为它返回的字符串列表中的单个字符串。如果您真的想使用.comb,一种方法是返回到原始正则表达式,但也可以使用正则表达式内的其他代码来存储所需的数据。
多个<(...)>并不意味着多次捕获
正则表达式整体匹配的默认起点是正则表达式的起点。默认终点是终点。
编写<(会将整体匹配的起点重置为插入它的位置。每次插入一个,并且在处理正则表达式时将其应用,它将重置起点。同样,)>重置终点。在处理正则表达式结束时,会将开始和结束的最终设置应用于构建最终的整体匹配。
假设您的代码无条件地将每个点重置了三次,那么最后的开始和结束将重置“win”。.comb将每个匹配项简化为单个字符串foo.comb(/.../)等效于foo.match(:g, /.../)>>.Str;
这意味着您与正则表达式的每次匹配只会得到一个字符串。
一种可能的解决方案是在其答案中使用@ohmycloudy显示的方法。
但这伴随着我和@ jubilatious1在评论他们的答案时提出的警告。
{ @comb-result .push: |$/».Str }添加到正则表达式
您可以解决.comb的正常功能。我并不是说这是一件好事。我也不是说不是。您问,我正在回答,仅此而已。 :)
从与其他解决方案一起使用的原始正则表达式开始。
然后将{ @comb-result .push: |$/».Str }添加到正则表达式的末尾以存储每个匹配项的结果。现在,您将获得所需的结果。

关于match - 为什么在 `<( )>`中多次使用 `comb` token 的行为不符合预期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64908692/

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