Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

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 (Bishop) 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
[chacham]: I'm sure this is old, but i just came across it: If you put a million monkeys at a million keyboards, one of them will eventually write a Java program. The rest of them will write Perl programs.
[LanX]: lol
[Corion]: Woo hoo! A new Auralnauts episode!
LanX mean unfair and funny
[LanX]: but most java code looks like from one million monkey using eclipse. ..

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (9)
As of 2018-04-23 16:00 GMT
Find Nodes?
    Voting Booth?