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 ); ... }