如何在 Perl 中用一个空格替换多个空格? [英] How can I replace multiple whitespace with a single space in Perl?

查看:116
本文介绍了如何在 Perl 中用一个空格替换多个空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这不起作用?

$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 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.

演示:

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

这篇关于如何在 Perl 中用一个空格替换多个空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆