in reply to Re^2: 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?
I don't recommend the following code anymore
rather
if ( my (@caps) = ($line =~ $re) ) { no warnings 'uninitialized'; @caps = () if $caps[0] ne $1; # reset pseudo capture +s $cb->(@caps); last; }
This should be backward compatible
my (@matches) = ($line =~ $re) if (defined $&) { $cb->(@matches); last; }
# tests...
use v5.12; use warnings; for my $str ("AB","") { say "****** str=<$str>"; for my $re ( qr/../, qr/(.)(.)/, q/XY/, q/(X)Y/, q// ) { say "--- re=<$re>"; my @captures = $str =~ $re; if ( defined $& ) { say "matched" } else { say "no match" } if (defined $1) { say "with captures <@captures>"; } else { say "no captures"; } } }
****** str=<AB> --- re=<(?^u:..)> matched no captures --- re=<(?^u:(.)(.))> matched with captures <A B> --- re=<XY> no match no captures --- re=<(X)Y> no match no captures --- re=<> matched no captures ****** str=<> --- re=<(?^u:..)> no match no captures --- re=<(?^u:(.)(.))> no match no captures --- re=<XY> no match no captures --- re=<(X)Y> no match no captures --- re=<> matched no captures
Cheers Rolf
(addicted to the 𐍀𐌴𐍂𐌻 Programming Language :)
Wikisyntax for the Monastery
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^4: How to know that a regexp matched, and get its capture groups?
by choroba (Cardinal) on Jan 10, 2023 at 12:17 UTC | |
by LanX (Saint) on Jan 10, 2023 at 12:24 UTC | |
by choroba (Cardinal) on Jan 10, 2023 at 12:30 UTC | |
Re^4: How to know that a regexp matched, and get its capture groups?
by LanX (Saint) on Jan 10, 2023 at 14:42 UTC | |
by AnomalousMonk (Archbishop) on Jan 11, 2023 at 06:22 UTC | |
by haukex (Archbishop) on Jan 11, 2023 at 09:27 UTC | |
by LanX (Saint) on Jan 11, 2023 at 11:30 UTC |