Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Regex question - identify which pattern comes first (named captures)

by LanX (Saint)
on May 02, 2026 at 15:18 UTC ( [id://11167684]=note: print w/replies, xml ) Need Help??


in reply to Regex question - identify which pattern comes first

requires 5.10 for named capture groups:

This code will even give you the sequence.

use v5.10; use strict; use warnings; my $str = "AB ABDA DCACCB AAA BSAA CAAB ACS ABA DBA BA DASSABACA A"; while ( $str =~ / (?<_1> BA[ABC]{2} ) | (?<_2> CA[CD]{2} ) | (?<_3> DA +[SC]{2} ) /gx) { print keys %+, " => ", values %+, " at pos ", pos($str), " \n"; }

_2 => CACC at pos 13 _3 => DASS at pos 48 _1 => BACA at pos 53

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

edit

  • inserted /x for readability
  • Replies are listed 'Best First'.
    Re^2: Regex question - identify which pattern comes first (named captures)
    by ikegami (Patriarch) on May 03, 2026 at 15:53 UTC

      Adjusted for OP:

      if ( $str =~ / (?: (?<_1> BA[ABC]{2} ) | (?<_2> CA[CD]{2} ) | (?<_3> DA[SC]{2} ) ) /x ) { my $first = substr( ( keys( %+ ) )[0], 1 ); ... }

      Update: Added missing ), as LanX pointed out.

    Log In?
    Username:
    Password:

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

    How do I use this?Last hourOther CB clients
    Other Users?
    Others musing on the Monastery: (1)
    As of 2026-05-12 16:18 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      No recent polls found

      Notices?
      hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
      erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.