Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

How to Modify Only Non-Quoted Words?

by ventolin (Novice)
on Aug 30, 2004 at 19:50 UTC ( #387014=perlquestion: print w/ replies, xml ) Need Help??
ventolin has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I'm a bit lost on the best solution - what's the best way to prefix every word in a string with the letter A except any words within quotes?

Thanks!

Comment on How to Modify Only Non-Quoted Words?
Re: How to Modify Only Non-Quoted Words?
by ikegami (Pope) on Aug 30, 2004 at 20:10 UTC
    $_ = q{ xxx "xxxxx xxx xxxx" 'xxxx xx xx' xxxx xxxx "xxxxx " "xxx" xxx }; s/ \G ( # $1 (?: (?:"(?:[^"\\]|\\.)*") # Skip double-quoted phrases. | (?:'(?:[^'\\]|\\.)*') # Skip single-quoted phrases. | \s # Skip whitespace. )* ) ( # $2 [^\s"']+ # Something to prefix. ) /$1A$2/gsx; print; __END__ output: ====== Axxx "xxxxx xxx xxxx" 'xxxx xx xx' Axxxx Axxxx "xxxxx " "xxx" Axxx
      Works great! Thanks!
Re: How to Modify Only Non-Quoted Words?
by ccn (Vicar) on Aug 30, 2004 at 20:36 UTC

    s { ([^"']*)? # non quoted part ("[^"]*")? # doublequoted ('[^']*')? # singlequoted } { my($x, $y, $z) = map {defined() ? $_ : ''} $1, $2, $3; $x =~ s/(?<!\S)(?=\S)/A/g; $x . $y . $z }xge;

      Don't know if it's relevant to the problem but both your and ikegami's solutions fail when contractions enter into the "word" list.

        If you want to escape quotes oustide of quoted strings, change

        ( # $2 [^\s"']+ # Something to prefix. )

        to

        ( # $2 (?:[^\s"'\\]|\\.)+ # Something to prefix. )
Re: How to Modify Only Non-Quoted Words?
by Your Mother (Canon) on Aug 31, 2004 at 06:44 UTC

    Don't get me wrong, I enjoyed reading both solutions. They break down on a string like: She said, 'I've known you can't since yesterday.' Not that it is necessarily relevant to OP's real problem.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://387014]
Approved by Old_Gray_Bear
Front-paged by grinder
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (11)
As of 2014-12-29 12:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (187 votes), past polls