On Tuesday, September 11, 2012 7:55:15 PM UTC-7, Jason C wrote:
> On Tuesday, September 11, 2012 4:50:20 PM UTC-4, C.DeRykus wrote:
>
>
>
> > One way to avoid an 'ee' solution's drawbacks
>
> > is just pull the backref out of the pattern:
>
> >
>
> > my $pattern = '(D|d)ear';
>
> > my $replace = 'eer';
>
> >
>
> > $text =~ s/$pattern/$1$replace/gi;
>
>
>
> That was my original thought, too, but I also have rows where the () isn't at the beginning. Eg:
>
>
>
> $pattern = 'smart(\s)*ass';
>
> $replace = 'smart$1butt';
>
>
>
> I really would like to avoid using /ee, though, for the security reasons mentioned earlier.
>
>
>
> Maybe something like:
>
>
>
> $text = "Yes dear!";
>
> $pattern = '(D|d)ear';
>
> $replace = '$1eer';
>
>
>
> # if $pattern doesn't contain a backreference
>
> # create an empty one
>
> if ($pattern !~ /\(.*?\)/g) {
>
> $pattern = "()*?" . $pattern;
>
> }
>
>
>
> $replace =~ s/\$1/<marker>/g;
>
> # now, $replace = '<marker>eer';
>
>
>
> while ($text =~ /$pattern/g) {
>
> $replace =~ s/<marker>/$1/g;
>
> $text =~ s/$pattern/$replace/gi;
>
> }
>
>
>
>
>
> I haven't tested that, I'm just spit-balling the logic. Thoughts?
I'm not sure I follow entirely but, IMO, separate regexes would be much easier and more maintainable
than trying to do this in a single regex.
Only if there's a huge bottleneck, would I bother,
trying to re-factor...
--
Charles DeRykus
|