in reply to Re^2: Regular expressions: Extracting certain text from a line
in thread Regular expressions: Extracting certain text from a line
Grrr! I wish they wouldn't do that.
Anticipating more ante upping, with deeply nested brace/bracket combos and wanting to capture a nested (but not an isolated) '{}' or '[]', e.g. '{ {} }', here's (maybe) a bit of a cheat:
#!/usr/bin/env perl -l use strict; use warnings; my ($brace_re, $bracket_re); $brace_re = qr< { (?: [^{}]++ | (??{ $brace_re }) )* } >x; $bracket_re = qr< \[ (?: [^\[\]]++ | (??{ $bracket_re }) )* \] >x; my $re = qr< ( $brace_re | $bracket_re ) >x; while (<DATA>) { print; while (/$re/g) { print "MATCH = $1" if length $1 > 2; } print '-' x 60; } __DATA__ ...?[](...$[] = [ USER_ENTITY_NAME ], text${} = { this is a test })... a[] = [ this is a [ test ] { test2 } ] a{} = { this is a { test } [ test2 ] } { a { b [ {}c{} ] d } e } = [ f [ g { []h[] } i ] j ] {}[]{ {}[] }[]{} - []{}[ []{} ]{}[]
Output:
...?[](...$[] = [ USER_ENTITY_NAME ], text${} = { this is a test })... MATCH = [ USER_ENTITY_NAME ] MATCH = { this is a test } ------------------------------------------------------------ a[] = [ this is a [ test ] { test2 } ] MATCH = [ this is a [ test ] { test2 } ] ------------------------------------------------------------ a{} = { this is a { test } [ test2 ] } MATCH = { this is a { test } [ test2 ] } ------------------------------------------------------------ { a { b [ {}c{} ] d } e } = [ f [ g { []h[] } i ] j ] MATCH = { a { b [ {}c{} ] d } e } MATCH = [ f [ g { []h[] } i ] j ] ------------------------------------------------------------ {}[]{ {}[] }[]{} - []{}[ []{} ]{}[] MATCH = { {}[] } MATCH = [ []{} ] ------------------------------------------------------------
Update: For Perl v5.8, you'll need to change [...]++ to (?> [...]+ ) (the '++' appeared in v5.10) and qr<...> delimiters will need to be something else, e.g. qr!...!.
The '(??{ $re })' construct has been around since at least v5.8.8.
Here's the perlre doco for 5.8.8 and 5.10.0.
-- Ken
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Regular expressions: Extracting certain text from a line
by AnomalousMonk (Archbishop) on Apr 09, 2014 at 01:23 UTC | |
by kcott (Archbishop) on Apr 09, 2014 at 03:08 UTC | |
by AnomalousMonk (Archbishop) on Apr 09, 2014 at 07:44 UTC | |
|
Re^4: Regular expressions: Extracting certain text from a line
by AnomalousMonk (Archbishop) on Apr 08, 2014 at 16:59 UTC |