gpt4 book ai didi

perl - 如何在 Perl 中用一个空格替换多个空格?

转载 作者:行者123 更新时间:2023-12-04 00:00:33 66 4
gpt4 key购买 nike

为什么这不起作用?

$data = "What    is the STATUS of your mind right now?";

$data =~ tr/ +/ /;

print $data;

最佳答案

使用 $data =~ s/ +/ /;反而。

解释:
trtranslation运算符(operator)。需要注意的重要一点是,正则表达式修饰符不适用于翻译语句(除了 - 仍然表示范围)。所以当你使用tr/ +/ /你说的是“获取字符空间和 + 的每个实例并将它们转换为一个空格”。换句话说,tr想到空间和+作为单个字符,不是 一个正则表达式。

示范:

$data = "What    is the STA++TUS of your mind right now?";

$data =~ tr/ +/ /;

print $data; #Prints "What is the STA TUS of your mind right now?"

使用 s通过说“匹配任意数量的连续空格(至少一个实例)并用一个空格替换它们”,可以满足您的要求。您可能还想使用类似的东西 s/ +/ /g;如果您希望替换的位置不止一个( g 意味着全局应用)。

关于perl - 如何在 Perl 中用一个空格替换多个空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3846931/

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