这个替换有什么问题吗?

发布于 2024-09-03 16:59:36 字数 193 浏览 10 评论 0原文

#!/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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

逆光飞翔i 2024-09-10 16:59:36

替换会替换整个单词 (\w+),然后替换一个空格,然后用下划线替换另一个单词。

实际上没有必要替换(或捕获重要的内容)这些单词

$a=~s/\b +\b/_/gm;

将替换分词符( \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

$a=~s/\b +\b/_/gm;

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.

网白 2024-09-10 16:59:36

这种模式替换可能是最有效的解决方案:

$a =~ s/\b \b/_/g;

This pattern replacement is probably the most efficient solution:

$a =~ s/\b \b/_/g;
牵你手 2024-09-10 16:59:36

如果没有涉及明确 look- 的答案,这个问题就不完整前向和后向断言

$s =~ s/(?<=\w) (?=\w+)/_/g
  • 这实际上与涉及零宽度字边界锚点 \b 的解决方案相同。

  • 请注意,前向正则表达式可以匹配任何字符长度的正则表达式,但后向正则表达式必须是固定长度的(这就是为什么 (?<=\w+) 可以'

This question wouldn't be complete without an answer involving explicit look-ahead and look-behind assertions:

$s =~ s/(?<=\w) (?=\w+)/_/g
  • 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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文