Pattern Matching & Replacement Prob

Kevin D. Clark kclark at elbrysnetworks.com
Wed Dec 20 12:28:57 EST 2006


Lawrence Tilly writes:

> What I need to do is this:
>   1.  Find the first ' and use it to flag the start of that segment.
>   2.  Continue thru the string until the next ' is encountered.
>   3.  If that ' is followed immediately by a comma ( no white space,
> etc.) mark that segment as complete and start again.
>   4.  If that ' is followed by any other character or white space,
> escape it by adding a second ' and then continue searching thru that
> segment.
>   5. Repeat #4 until #3 occurs since the user may have typed more than
> one word with an apostrophe in it in the same comment block.

So you want this:

  'It's Dan's',
  'If you go to Z'ha'dum, you will die',  'It's Spencers' toy'

transformed to this?

  'It''s Dan''s'
  'If you go to Z''ha''dum, you will die',  'It''s Spencers'' toy',


How about:

  #!/usr/bin/perl -p
  
  # Lawrence's definition of a string
  #
  # (well, I added "end-of-line" as being an acceptable end of 
  # a single-quoted string...) 
  
  $stringre = qr/'(.*?)'(?:,|$)/;   # Note: this sets $1
  
  
  s/$stringre/($replace = $1) =~ s#'#''#g; "'$replace',"/ge;

  __END__


It's a little tricky to do what you want, but Perl's regexp engine is
very powerful...

Regards.

--kevin
-- 
GnuPG ID: B280F24E              Never could stand that dog.
alumni.unh.edu!kdc                   -- Tom Waits



More information about the gnhlug-discuss mailing list