in reply to Re: Replace zero-width grouping?
in thread Replace zero-width grouping?
#!/usr/bin/perl -wl use strict; my $str = "17341234173412341734123417341234"; { local *_ = \$str; *_ = \substr $_, pos()-4 while s/(.)(...)\1/A$2B/; } print $str;
I am exploiting the fact that assigning a ref to something to a glob creates an alias to that something; this also works for a ref to an lvalue such as substr returns. Only when a match happens, the substitution is restarted, and then in order to avoid rescanning, I hide the already processed front of the string by aliasing $_ to the unprocessed portion. In the ideal case of no match, this means the RE engine will only be invoked once, regardless of the string's length.
Unfortunately, it doesn't work in this simple form because alas, s/// does not leave pos in a useful state after a substitution. The real code thus needs an ugly temporary variable and a messy addition to the substitution:
my $i = 0; *_ = \substr $str, $i while s/(.)(...)\1(?{ $i += pos() - 4 })/A$2 +B/;
The result is A7AAB2BBA7AAB2BBA7AAB2BBA7AAB2BB.
Update: I just noticed this is essentially the same as diotalevi is doing. Doh.
Makeshifts last the longest.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re^2: Replace zero-width grouping?
by BrowserUk (Patriarch) on May 08, 2003 at 21:56 UTC | |
by Aristotle (Chancellor) on May 09, 2003 at 06:22 UTC | |
by BrowserUk (Patriarch) on May 09, 2003 at 07:24 UTC | |
by Aristotle (Chancellor) on May 09, 2003 at 09:55 UTC | |
by BrowserUk (Patriarch) on May 09, 2003 at 15:37 UTC | |
| |
by diotalevi (Canon) on May 09, 2003 at 13:41 UTC | |
| |
by hv (Prior) on May 09, 2003 at 11:36 UTC |