Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: mysteries of regex substring matching

by LanX (Saint)
on Jan 15, 2021 at 22:34 UTC ( [id://11126979]=note: print w/replies, xml ) Need Help??


in reply to mysteries of regex substring matching

> So, is there a way to use capture groups to match multiple times like separate groups does in the first example?

It depends what your goal is.

If it's simply using a quantifier {4} the answer is no, because only the last match will be kept for the unique first group , that's why you get 01D9 at the end. Not a mystery.

But there are numerous workarounds I can think of.

Like

  • using the /g modifier in a loop /(....)/g
  • reading the last capture with embedded Perl code like /(....(?{print $1})){4}/

updates
  • minor corrections
  • links to perlretut

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery

Replies are listed 'Best First'.
Re^2: mysteries of regex substring matching
by LanX (Saint) on Jan 15, 2021 at 22:45 UTC
    > using the /g modifier in a loop /(....)/g

    demo:

    DB<53> $x = q[AAD34017837201D98AAED18778DEF993]; DB<54> $x =~ m/(....)/g and say $1 for 1..4 AAD3 4017 8372 01D9 DB<55>

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery

Re^2: mysteries of regex substring matching
by LanX (Saint) on Jan 15, 2021 at 22:53 UTC
    > reading the last capture with embedded Perl code like /(....(?{print $1})){4}/

    demo: (using /x for clarification)

    DB<66> $x = q[AAD34017837201D98AAED18778DEF993]; DB<67> $x =~ m/(?: (....) (?{say $1}) ) {4} /x AAD3 4017 8372 01D9 DB<68>

    update

    I think this explains your "mystery", they all match but only the last one is kept in $1.

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (3)
As of 2024-04-26 04:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found