正则表达式中的空格字符无法识别

时间:2023-02-12 20:13:36

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.

我正在编写一个简单的程序 - 请参阅下面的代码和评论。有谁知道为什么第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";

4 个解决方案

#1


16  

Try s/::/ /g instead of s/::/\s/g.

尝试使用s / :: / / g而不是s / :: / \ 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实际上是一个表示所有空白字符的字符类,因此将它放在正则表达式(第一部分)而不是替换字符串中才有意义。

#2


3  

Use s/::/ /g. \s only denotes whitespace on the matching side, on the replacement side it becomes s.

使用s / :: / / g。 \ s仅表示匹配侧的空白,在替换侧它变为s。

#3


3  

Replace the \s with a real space.

用真实空间替换\ s。

The \s is shorthand for a whitespace matching pattern. It isn't used when specifying the replacement string.

\ s是空白匹配模式的简写。指定替换字符串时不使用它。

#4


3  

Replace string should be a literal space, i.e.:

替换字符串应该是文字空间,即:

$string =~ s/::/ /g;

#1


16  

Try s/::/ /g instead of s/::/\s/g.

尝试使用s / :: / / g而不是s / :: / \ 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实际上是一个表示所有空白字符的字符类,因此将它放在正则表达式(第一部分)而不是替换字符串中才有意义。

#2


3  

Use s/::/ /g. \s only denotes whitespace on the matching side, on the replacement side it becomes s.

使用s / :: / / g。 \ s仅表示匹配侧的空白,在替换侧它变为s。

#3


3  

Replace the \s with a real space.

用真实空间替换\ s。

The \s is shorthand for a whitespace matching pattern. It isn't used when specifying the replacement string.

\ s是空白匹配模式的简写。指定替换字符串时不使用它。

#4


3  

Replace string should be a literal space, i.e.:

替换字符串应该是文字空间,即:

$string =~ s/::/ /g;