Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

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?


Replies are listed 'Best First'.
Re: How to Modify Only Non-Quoted Words?
by ikegami (Patriarch) 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. )


        ( # $2 (?:[^\s"'\\]|\\.)+ # Something to prefix. )
Re: How to Modify Only Non-Quoted Words?
by Your Mother (Archbishop) 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?

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

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2022-11-30 20:22 GMT
Find Nodes?
    Voting Booth?