How can I replace multiple whitespace with a single space in Perl?

巧了我就是萌 提交于 2020-08-22 09:34:40

问题


Why is this not working?

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

$data =~ tr/ +/ /;

print $data;

回答1:


Use $data =~ s/ +/ /; instead.

Explanation:

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 use
tr/ +/ / 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.

Demonstration:

$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?"

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 like
s/ +/ /g; if there's more than one place you want the substitution to occur (g meaning to apply globally).




回答2:


You can also use tr with the "squash" option, which will remove duplicate replaced characters. See perlop for details.

my $s = "foo      bar   fubb";
$s =~ tr/ //s;



回答3:


Perl 5.10 has a new character class, \h, the stands for horizontal whitespace which is nice for this sort of thing:

 $s =~ s/\h+/ /g;


来源:https://stackoverflow.com/questions/3846931/how-can-i-replace-multiple-whitespace-with-a-single-space-in-perl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!