kurotsuki
kurotsuki

Reputation: 4777

Space character in regex is not recognised

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";

Upvotes: 5

Views: 17890

Answers (4)

Andrew Kolesnikov
Andrew Kolesnikov

Reputation: 1893

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

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

Upvotes: 3

Raymond Hettinger
Raymond Hettinger

Reputation: 226346

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.

Upvotes: 4

Tikhon Jelvis
Tikhon Jelvis

Reputation: 68152

Try s/::/ /g instead of 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.

Upvotes: 16

Fred Foo
Fred Foo

Reputation: 363607

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

Upvotes: 4

Related Questions