Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

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 (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. )


        ( # $2 (?:[^\s"'\\]|\\.)+ # Something to prefix. )
Re: How to Modify Only Non-Quoted Words?
by Your Mother (Chancellor) 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
Node Status?
node history
Node Type: perlquestion [id://387014]
Approved by Old_Gray_Bear
Front-paged by grinder
[Lady_Aleena]: shmem, there is ONE song which throws a wrench in the works for both MP3::Info and MP3::Tag.
[shmem]: Lady_Aleena: fix it, or delete it ;-)
[Lady_Aleena]: shmem, I'm not sure how.
[shmem]: well, deleting is done with 'rm' :-P
[shmem]: you can break up the chain MP3::Tag->new($_)- >interpolate("\%S ") and test whether MP3::Tag->new($_) is true
[Lady_Aleena]: shmem, no to deletion.

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (5)
As of 2017-04-23 22:12 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (432 votes). Check out past polls.