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

Hi monks,

In the following regex, I'm trying to escape the single quote mark in words with an apostrophe 's':

my $string = qq~'tom's is silly','some','peter said it's okay'~; $string =~ s/(?!,)'s/\\'s/g; print "$string\n"; #output: 'tom\'s silly',\'some','peter said it\'s okay' #desired output: 'tom\'s is silly','some','peter said it\'s okay' # In the desired output, the single quote before "some" is not escaped
The text in $string is the dumped output from MySQL. $string contains the 3 values (1) "tom's silly" (2) "some" and (3) "peter said it's okay"

I need to escape the single quote mark in "tom's" and "it's". My regex escapes the single quote before "some" as well, which is wrong.

Please enlighten me.

Thanks in advance :)

Replies are listed 'Best First'.
Re: Escape single quote marks in words
by runrig (Abbot) on May 27, 2004 at 16:39 UTC
    You want a negative look-behind assertion (?<!...), not a look-ahead.
      Thanks, runrig!

      It works now :)

Re: Escape single quote marks in words
by hv (Prior) on May 27, 2004 at 17:00 UTC

    The easiest way to think of this may be:

    replace ' with \' if it lies between two letters
    .. which you can do like this:
    s/(?>=\w)'(?=\w)/\\'/g;
    .. or like this:
    s/\b'\b/\\'/g;

    Hugo

      Thanks, Hugo!

      Your regex is more precise and less prone to errors than the one I've, which uses a comma as the context.