1

I'm having problems while replacing metacharacters using regular expressions. The phrase I want the regular expressions replace the metacharacter is:

ley+sobre+propiedad+literaria+1847

And the code I use is that below:

$file =~ s/\+/\s/; # --> Replace the +

But it seems to only replace the first metacharacter and the result is:

leysobre+propiedad+literaria+1847

What shoud I use?

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Marc Ortiz
  • 2,242
  • 5
  • 27
  • 46
  • 1
    You might make it more readable by using a character class `[+]` instead of `\+`. But that's just a preference :) – HamZa Aug 14 '13 at 10:27

3 Answers3

6
  1. The \s is a character class and not a valid escape for strings. The second part of a substitution is taken as a string.
  2. To replace all occurrences (“globally”), use the /g switch on the replacement.
  3. Single-character transliterations can also use the tr/// operator.

Assuming you want to replace + by a space:

tr/+/ /;

or

s/\+/ /g;

If you want to decode URLs:

use URL::Encode 'url_decode';
my $real_filename = url_decode $file;

See the documentation for URL::Encode for further information.

amon
  • 57,091
  • 2
  • 89
  • 149
3

Your problem is not connected to metacharacters. The substitution s/// replaces only the first occurrence of the pattern unless told to replace all of them by the /g option.

BTW, \s is interpreted as plain s in the replacement part. If you want \s, you have to specify \\s to backslash the backslash (as in double quotes). Thus the output is in fact

leyssobre+propiedad+literaria+1847

Note the double s.

choroba
  • 231,213
  • 25
  • 204
  • 289
1

use the s/\+/ /g to replace globally.

collapsar
  • 17,010
  • 4
  • 35
  • 61