这个替换有什么问题吗?
#!/usr/bin/perl
use strict;
use warnings;
my $s = "sad day
Good day
May be Bad Day
";
$s =~ s/\w+ \w+/_/gm;
print $s;
我试图用 _ 替换单词之间的所有空格,但它不起作用。这有什么问题吗?
#!/usr/bin/perl
use strict;
use warnings;
my $s = "sad day
Good day
May be Bad Day
";
$s =~ s/\w+ \w+/_/gm;
print $s;
I am trying to substitute all spaces between words with _, but it is not working. What is wrong with that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
替换会替换整个单词 (
\w+
),然后替换一个空格,然后用下划线替换另一个单词。实际上没有必要替换(或捕获重要的内容)这些单词
将替换分词符(
\b
,单词和非单词之间的零宽度转换),后跟一个或多个空格后跟另一个分词符和下划线。使用\b
可确保您不会替换新行前后的空格。The substitution replaces an entire word (
\w+
) then a space then an other word by an underscore.There is really no need to replace (or capture for what matters) those words
will replace a word break (
\b
, a zero-width transition between a word and a non word) followed by one or more spaces followed by an other word break, by an underscore. Using\b
ensures that you don't replace a space after or before a new line.这种模式替换可能是最有效的解决方案:
This pattern replacement is probably the most efficient solution:
如果没有涉及明确 look- 的答案,这个问题就不完整前向和后向断言:
这实际上与涉及零宽度字边界锚点
\b
的解决方案相同。请注意,前向正则表达式可以匹配任何字符长度的正则表达式,但后向正则表达式必须是固定长度的(这就是为什么
(?<=\w+)
可以'This question wouldn't be complete without an answer involving explicit look-ahead and look-behind assertions:
This is effectively the same as the solutions involving the zero-width word-boundary anchor,
\b
.Note that look-ahead regexes can match regexes of any character length, but look-behind regexes have to be of fixed-length (which is why
(?<=\w+)
can't be done).