gpt4 book ai didi

regex - 拆分不起作用(Perl)

转载 作者:行者123 更新时间:2023-12-01 10:50:52 25 4
gpt4 key购买 nike

我一直在尝试执行以下代码;但是@ans 最终会包含 $answer 的全部内容。

$answer = "6.9 4012 top 5.6 2868 top 5.0 3686 top 4.7 5128 top 4.5 3120 top";
@ans = split('/ /',$answer);
foreach (@ans) {
print "$_\n";
}

在这种情况下,我想根据空格进行拆分。请你能告诉我这段代码有什么问题吗?

最佳答案

您使用 split 不正确。这将起作用:

@ans = split(' ', $answer);

还有这个:
@ans = split(/ /, $answer);

请注意, split 的第一个参数不是字符串,而是正则表达式。以下拆分表达式的所有变体都给出了相同的结果:
' ' , / / , " " , m/ / , m' ' , qr/ / , qr' ' , qr{ } .
/str/的用法for regex 有点类似于 match regex 在表达式中的用法:
my ($x) = ($str =~ /(w+)/);

或者
my ($x) = ($str =~ m/(w+)/);

更新 :感谢@mpapec,有一个关于 ' ' 的问题对比 / /来自 perldoc -f split :

As a special case, specifying a PATTERN of space (' ') will split on white space just as "split" with no arguments does. Thus, "split(' ')" can be used to emulate awk's default behavior, whereas "split(/ /)" will give you as many initial null fields (empty string) as there are leading spaces.



换句话说, split(' ', " x y ")返回 ('x', 'y') ,但是 split(/ /, " x y ")返回 ('', 'x', 'y') .

关于regex - 拆分不起作用(Perl),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20677757/

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