Pattern Matching & Replacement Prob

Lawrence Tilly mail.list.tilly at gmail.com
Wed Dec 20 12:58:19 EST 2006


On 12/20/06, Kevin D. Clark <kclark at elbrysnetworks.com> wrote:
>
> 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
>

The folks here never cease to amaze me with the rapid response.  I
know it was a pretty messy requst.  My awk was looking more and more
ugly and I figured Perl would be the better tool for the job.  It
looks like you defined it well with your solution.  I'm going to give
it a try against some test files in the next day or two and see how it
does.  Even if it isn't 100%, I am usually able to tweak Perl as long
as I have something to work off of...it's trying to start from scratch
that's been my problem.

Of course, I'm almost obligated to try this simply because of the very
good use of a B5 quote.  :-)

-Lawrence


More information about the gnhlug-discuss mailing list