Rexexp on part of a string
Ovid
publiustemp-londonpm at yahoo.com
Tue Feb 19 12:00:05 GMT 2008
--- virtualsue <virtuallysue at gmail.com> wrote:
> >> I would like to restrict the part of a string a regexp is allowed
> >> to operate on, For example I would like to ignore comments.
> >> I would like
> >>
> >> $x = " andrew andrew # andrew " ;
> >> $x =~ s/andrew/black/g ;
> >> to produce " black black # andrew "
<snip>
> > you could simply split() on #, s/andrew/black/g and rejoin
> > or use a lookahead
> > s/andrew(?=.*\#)/black/g;
>
> If I split on # then what happens if $x contains 'print
> "==#andrew#andrew#===\n" # more andrew'?
>
> Maybe the data would never look like that, but calling them comments
> and using the '#' to delineate them makes you wonder.
I think the problem here is that we have an example of the data rather
than a specification of it. The latter would make the question far
easier to answer :)
And if splitting the data makes sense, my Data::Record might come in
handy (http://search.cpan.org/dist/Data-Record/) because it gives the
programmer very fine-grained control over how to split data:
use Regexp::Common;
use Data::Record;
my $record = Data::Record->new({
split => "\n",
unless => $RE{quoted},
});
my @data = $record->records($data);
Cheers,
Ovid
--
Buy the book - http://www.oreilly.com/catalog/perlhks/
Perl and CGI - http://users.easystreet.com/ovid/cgi_course/
Personal blog - http://publius-ovidius.livejournal.com/
Tech blog - http://use.perl.org/~Ovid/journal/
More information about the london.pm
mailing list