正则表达式中的空格字符无法识别
我正在编写一个简单的程序 - 请参阅下面的代码和注释。有谁知道为什么第 10 行无法识别空格字符?当我运行代码时,它找到 :: 但不会将其替换为空格。
1 #!/usr/bin/perl
2
3 # This program replaces :: with a space
4 # but ignores a single :
5
6 $string = 'this::is::a:string';
7
8 print "Current: $string\n";
9
10 $string =~ s/::/\s/g;
11 print "New: $string\n";
I'm writing a simple program - please see below for my code with comments. Does anyone know why the space character is not recognised in line 10? When I run the code, it finds the :: but does not replace it with a space.
1 #!/usr/bin/perl
2
3 # This program replaces :: with a space
4 # but ignores a single :
5
6 $string = 'this::is::a:string';
7
8 print "Current: $string\n";
9
10 $string =~ s/::/\s/g;
11 print "New: $string\n";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试使用
s/::/ /g
而不是s/::/\s/g
。\s
实际上是一个代表所有 空白字符的字符类,因此只有将其放在正则表达式(第一部分)中而不是放在替换字符串中才有意义。Try
s/::/ /g
instead ofs/::/\s/g
.The
\s
is actually a character class representing all whitespace characters, so it only makes sense to have it in the regular expression (the first part) rather than in the replacement string.使用
s/::/ /g
。\s
仅表示匹配侧的空白,在替换侧则变为s
。Use
s/::/ /g
.\s
only denotes whitespace on the matching side, on the replacement side it becomess
.将
\s
替换为真实的空格。\s
是空白匹配模式的简写。指定替换字符串时不使用它。Replace the
\s
with a real space.The
\s
is shorthand for a whitespace matching pattern. It isn't used when specifying the replacement string.替换字符串应该是文字空格,即:
Replace string should be a literal space, i.e.: