mirod has asked for the wisdom of the Perl Monks concerning the following question:
This bugged me for a while so I thought I'd mention the solution I found, as well as ask if there is a better way to do it:
Basically I wanted to do a rather complex substitution globally but /g did not work for me. The reason /g did not work is that I need part of the string that has already be used in order to do each match.
I guess a simple example will illustrate the problem better: in the string 'a1b1a2b1b2a3b1b2b3'db1b2 I want to move all the b\d+ following a\d+ to the end of the string and wrap them in (). In this case the simple s{(a\d+)(b\d+)(.*)}{$1$3($2)}g will not work: it will only move the first b, as the regexp engine has to go all the way to the end of the string to match the (.*) part.
There might be ways to do this in one substitution, and I'd like to hear about them, but in fact the real regexps are a bit more complex, so easy tricks are not likely to work, I have searched for them for a while ;--( The main problems are that the (a\d+) is of variable length, which prevents using a look behind (?<=a\d+), each (b\d+) has to be processed separately, and the final (.*) will go through the whole string anyway...
In any case here is the solution I found: use a while with an empty body: while( $string=~ s{(a\d+)(b\d+)(.*)}{$1$3($2)}){}. This works fine, is conceptually clean, but I don't like the empty {}, it looks just weird. Which makes me wonder if there is an other way to do this, one that would be blessed by better hackers than me?
Here is a toy script if you want to play with the problem:
#!/bin/perl -w use strict; while( my $string=<DATA>) { # this works while( $string=~ s{(a\d+)(b\d+)(.*)}{$1$3($2)}){} # this does not #$string=~ s{(?<=a\d+)(b\d+)(.*)}{$3($2)}g; print "string: $string\n"; } __DATA__ a1b1b2b3 a1b1a12b1b2a3b1b2b3db1b2
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Real global substitution, what's the best way?
by blakem (Monsignor) on Dec 08, 2001 at 02:11 UTC | |
|
Re: Real global substitution, what's the best way?
by dws (Chancellor) on Dec 08, 2001 at 00:42 UTC | |
by mirod (Canon) on Dec 08, 2001 at 00:50 UTC | |
|
(tye)Re: Real global substitution, what's the best way?
by tye (Sage) on Dec 08, 2001 at 12:32 UTC | |
|
Re: Real global substitution, what's the best way?
by dragonchild (Archbishop) on Dec 08, 2001 at 00:40 UTC | |
|
Re: Real global substitution, what's the best way?
by traveler (Parson) on Dec 08, 2001 at 01:21 UTC |