Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: How to access last capture groups outside regex using interpolation but w/o using re 'eval'?

by AnomalousMonk (Bishop)
on Jun 16, 2020 at 22:16 UTC ( #11118152=note: print w/replies, xml ) Need Help??


in reply to How to access last capture groups outside regex using interpolation but w/o using re 'eval'?

One way:

c:\@Work\Perl\monks>perl -wMstrict -le "use 5.010; ;; use warnings; use strict; ;; use Test::More 'no_plan'; use Test::NoWarnings; ;; use Data::Dump qw(dd pp); ;; my @TESTS = ( [ '', [ 1, ], [ ], ], [ 'c', [ 1, ], [ qw(c) ], ], [ 'c', [ 2, ], [ ], ], [ 'cba', [ 1, ], [ qw(c) ], ], [ 'cbaa', [ 1, 2, ], [ qw(c aa) ], ], [ 'bbaa', [ 1, 2, ], [ qw(b aa) ], ], [ 'cccqrrtaaa', [ 1, 1, 1, 1, 3, ], [ qw(c q r t aaa) ], ], [ 'cccqrrtaaa', [ 2, 2, 2, ], [ qw(cc rr aa) ], ], [ 'cccqrrtaaa', [ 1, 1, 2, 2, ], [ qw(c q rr aa) ], ], ); ;; VECTOR: for my $ar_vector (@TESTS) { if (not ref $ar_vector) { note $ar_vector; next VECTOR; } ;; my ($string, $ar_groups, $ar_expected) = @$ar_vector; ;; my $rx = build_regex($ar_groups); ;; my @groups = extract_groups($string, $rx); ;; is_deeply \@groups, $ar_expected, qq{'$string' <- (@$ar_groups) -> (@$ar_expected)} } ;; done_testing; ;; exit; ;; ;; sub build_regex { my ($ar_groups) = @_; ;; my ($rx) = map qr{ $_ }xms, join ' .*? ', map qr{ ((.) \g-1{$_} (?! \g-1)) }xms, map $_-1, @$ar_groups ; ;; return $rx; } ;; sub extract_groups { my ($string, $rx) = @_; ;; my $p; return grep $p = !$p, $string =~ $rx ; } " ok 1 - '' <- (1) -> () ok 2 - 'c' <- (1) -> (c) ok 3 - 'c' <- (2) -> () ok 4 - 'cba' <- (1) -> (c) ok 5 - 'cbaa' <- (1 2) -> (c aa) ok 6 - 'bbaa' <- (1 2) -> (b aa) ok 7 - 'cccqrrtaaa' <- (1 1 1 1 3) -> (c q r t aaa) ok 8 - 'cccqrrtaaa' <- (2 2 2) -> (cc rr aa) ok 9 - 'cccqrrtaaa' <- (1 1 2 2) -> (c q rr aa) 1..9 ok 10 - no warnings 1..10
Now let's see the rest of the specification. :)

Update: This code needs Perl version 5.10+ only because it uses the \g{n} relative backreference.


Give a man a fish:  <%-{-{-{-<

  • Comment on Re: How to access last capture groups outside regex using interpolation but w/o using re 'eval'?
  • Select or Download Code

Replies are listed 'Best First'.
Re^2: How to access last capture groups outside regex using interpolation but w/o using re 'eval'?
by rsFalse (Hermit) on Jun 17, 2020 at 07:00 UTC
    Thanks! Nice simplification and improvement!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11118152]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2020-11-30 02:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?