Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

substitute with space

by vitaly (Acolyte)
on Sep 10, 2007 at 01:54 UTC ( [id://637967]=perlquestion: print w/replies, xml ) Need Help??

vitaly has asked for the wisdom of the Perl Monks concerning the following question:

I got $keyword like XXX+UUU+CCC from ...(...)... in reg. expr. Trying to substitute all + with spaces I got an empty result. What am I doing wrong? ............ my $keyword = $2; $keyword =~ s/\+/\s/g; Thanks, Vitaly

Replies are listed 'Best First'.
Re: substitute with space
by Zaxo (Archbishop) on Sep 10, 2007 at 04:37 UTC

    Another way is to transliterate;

    $keyword =~ tr/+/ /;
    That's quicker and a little simpler, since the regex engine isn't invoked.

    After Compline,
    Zaxo

Re: substitute with space
by mr_mischief (Monsignor) on Sep 10, 2007 at 02:01 UTC
    Don't use a character class on the replacement side of a search/replace. If you want a space, use ' '. Even if \s worked there, it'd be ambiguous since it could be a space, a tab, or something else. See perlre.
      When using $keyword =~ s/\+/' '/g; After replacement of Auto+Recycling+%26+Dismantling I got Auto' 'Recycling' '%26' 'Dismantling Instead of Auto Recycling %26 Dismantling
        Don't include the quotes. The quotes are there in my node to quote the string. They are not part of the string they are quoting.
Re: substitute with space
by graff (Chancellor) on Sep 10, 2007 at 02:06 UTC
    You left out a few important details (and code tags). What was the original string, and the actual regex that was supposed to apply for extracting $keyword?

    An empty result means that your initial regex match is not working as expected, so if you showed us the original string and the initial regex, we'd be able to tell you why it failed.

    If your initial regex only had one set of parens, then there is no $2 that results from the match -- you need to use $1 instead. Apart from that, if a string contains "+", then your statement  s/\+/\s/g will replace each "+" with a literal "s" -- things like "\s, \d, \b" don't work in the right-hand (replacement) side like they do in the left-hand (match) side (but things like "\n, \t, \r" do).

    You want to say  s/\+/ /g instead.

    P.S.: learn about using code tags by looking at Writeup Formatting Tips. You'll see a link to that page every time you preview a new post. Use it.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://637967]
Approved by graff
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (8)
As of 2024-03-28 10:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found