in reply to Re^4: How to know that a regexp matched, and get its capture groups?
in thread How to know that a regexp matched, and get its capture groups?
if ( my (@caps) = ($line =~ $re) ) { @caps = () if $caps[0] ne $1; # reset pseudo captures $cb->(@caps); last; }
In
@caps = () if $caps[0] ne $1;
$1 will be undefined if there is no capture group 1 or it is something like (...)? that fails to match
(but an overall match can still occur). Warnings will be generated.
Although it's only compatible back to version 5.6, an alternative would be
c:\@Work\Perl\monks>perl use strict; use warnings; use Data::Dump qw(pp); my $cb = sub { print "matched, captured ", pp @_; }; for my $str ("AB","") { for my $re (qr/../, qr/(.)(.)/, qr/(X)?(.)/, qr/XY/, qr/(X)Y/, qr/ +/) { print "str <$str> re $re "; if ( my (@caps) = ($str =~ $re) ) { # @caps = () if $caps[0] ne $1; # reset pseudo capture $#caps = $#- - 1; # reset pseudo capture $cb->(@caps); } else { print 'NO match'; } print "\n"; } } ^Z str <AB> re (?-xism:..) matched, captured () str <AB> re (?-xism:(.)(.)) matched, captured ("A", "B") str <AB> re (?-xism:(X)?(.)) matched, captured (undef, "A") str <AB> re (?-xism:XY) NO match str <AB> re (?-xism:(X)Y) NO match str <AB> re (?-xism:) matched, captured () str <> re (?-xism:..) NO match str <> re (?-xism:(.)(.)) NO match str <> re (?-xism:(X)?(.)) NO match str <> re (?-xism:XY) NO match str <> re (?-xism:(X)Y) NO match str <> re (?-xism:) matched, captured ()
Update: But see haukex's reply about the preference for $#+ versus $#- (@+ versus @-) regex special variables.
Give a man a fish: <%-{-{-{-<
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^6: How to know that a regexp matched, and get its capture groups?
by haukex (Archbishop) on Jan 11, 2023 at 09:27 UTC | |
Re^6: How to know that a regexp matched, and get its capture groups?
by LanX (Saint) on Jan 11, 2023 at 11:30 UTC |