In view of the alternation, perhaps OP means that the intent is to print that part of the regex that produced the match.

That could be achived by using multiple regexen instead of alternation:

#!/usr/bin/perl use strict; use warnings; use 5.012; # #926110 my $regex1 = qr/foo\d+/; my $regex2 = qr/bar\S+?/; my @string = qw(foo17 barABC nomatch); for my $string(@string) { if ($string =~ m/($regex1)/ && $regex1 =~ /(.*)/s) { say "$1 when string is \"$string\""; } elsif ( $string=($regex2) && $regex2 =~ /(.*)/s ) { say "$1 when string is \"$string\""; } else { say "no match on $string"; } }
which produces this:
(?-xism:foo\d+) when string is "foo17" (?-xism:bar\S+?) when string is "barABC" (?-xism:bar\S+?) when string is "nomatch"

Update: Or, better (simpler and more info in output):

hashbang, strict, warn, etc... my $regex1 = qr/foo\d+/; my $regex2 = qr/bar\S+?/; my @string = qw(foo17 barABC this-has-no-match); for my $string(@string) { if ($string =~ m/($regex1)/) { say "matched part of \"$string\" is $1 when regex is \"$r +egex1\""; next; } elsif ( $string=~ m/($regex2)/ ) { say "matched part of \"$string\" is $1 when regex is \"$regex2 +\""; next; } else { say "no match on $string"; } }
outputting:
matched part of "foo17" is foo17 when regex is "(?-xism:foo\d+)" matched part of "barABC" is barA when regex is "(?-xism:bar\S+?)" no match on this-has-no-match

In reply to Re: Regex: return the pattern instead of the actual match by ww
in thread Regex: return the pattern instead of the actual match by Deus Ex

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.