in reply to Regex to strip, keep, or add—depending
The following monstrosity accounts for nested parens, and also isn't limited to the start of line; it tries to avoid messing with things that don't look like function calls. This DOESN'T work on the last example (nested function calls which need to be fixed). I'm sure there are some other quirks to Perl syntax which this doesn't catch.
use Regexp::Common qw/balanced/; while (<DATA>) { chomp; my $bp = qr/$RE{balanced}{-parens=>'()'}{-keep}/; $_ =~ s{ &? # optional & ( # capture either: (?<=&) \w+ # bareword preceeded by & | # or \w+ (?=\s*\() # bareword followed by ( ) # (?: \s* (?=\())? # optional white space, if followed by ( (?: # either: $bp # balanced parens | # or # nothing! ) } # if no second capture, supply an empty () { $1 . ($2 || '()') }exg; print "$_\n"; } __DATA__ &foobar &foobar() foobar() &foobar("asdf") &foobar( test(), qw(etc.)) &foobar( test(test() . test()) ) &foobar("a", 5, qw(dave jen anne matt), map({tr/[a-z]/[A-Z]/; $_;} @mi +xedCase)); &dont_change if not &function() &foobar ('<- white space?') &foobar( &test_nested )
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Regex to strip, keep, or add—depending
by JediWizard (Deacon) on Aug 06, 2005 at 16:46 UTC | |
by chester (Hermit) on Aug 06, 2005 at 17:27 UTC | |
by BUU (Prior) on Aug 06, 2005 at 22:50 UTC |