[TxMt] OT: Perl Compatible Regex problem I can't solve

Paul McCann pmccann at gmail.com
Fri Apr 8 06:11:17 UTC 2005


Dave wrote...

> It doesn't match them all in one match, but loops destructively against each
> line. It's also less preferable than a split, unless you're expecting input
> which contains slashes and doesn't otherwise match your criteria.

split is definitely the way to go for this problem (if shelling out
isn't against the rules!).
 
> I realised when attempting this I have no idea how to make captured matches
> not overwrite each other - eg running /^(?:(\w+) ?)$/ against 'foo bar baz
> woz' returns only $1=woz; previous matches (foo etc) are overwritten.
> 
> If anyone knows how to alleviate that, it's driving me mental ..

There is no way: the variables $1, $2 etc are reset on every
successful use a regex, even when the regex does not capture output
via parentheses. This is as it should be (otherwise you'd get all
sorts of leftover nonsense down the track). Just grab what you want at
the time the regex runs.

Trying to mimic your solution with some personal preferences mixed in produced

#!/usr/bin/perl -w
my $string=('/a/b/c/d/efgh/joke/345/');
my @found=($string=~m|/?([^/]+)/?|g);
print join "\n", at found;

(I've used | | as the regex delimiters to stop all the leaning
toothpicks, and have used a global match rather than a substitution.
In list context (as here) all the matches are returned, so I've
captured them in the array @found.)

Best wishes,
Paul



More information about the textmate mailing list