问题描述
为什么这不起作用?
$data = "What is the STATUS of your mind right now?";
$data =~ tr/ +/ /;
print $data;
推荐答案
使用 $data =~ s/+//;
代替.
说明:
tr
是翻译操作员.需要注意的重要一点是,正则表达式修饰符不适用于翻译语句(除了 -
仍然表示范围).所以当你使用tr/+//
你是说获取字符空格和 +
的每个实例并将它们转换为空格".换句话说,tr
将空格和 +
视为单个字符,不是正则表达式.
The tr
is the translation operator. An important thing to note about this is that regex modifiers do not apply in a translation statement (excepting -
which still indicates a range). So when you usetr/ +/ /
you're saying "Take every instance of the characters space and +
and translate them to a space". In other words, the tr
thinks of the space and +
as individual characters, not a regular expression.
演示:
$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
意味着全局应用).
Using s
does what you're looking for, by saying "match any number of consecutive spaces (at least one instance) and substitute them with a single space". You may also want to use something likes/ +/ /g;
if there's more than one place you want the substitution to occur (g
meaning to apply globally).
这篇关于如何在 Perl 中用一个空格替换多个空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!