The straightforward solution is to actually combine the regular expressions and eliminate the $end_of_path variable:

my $path = '/.snapshots123/yabsm/root/hourly/day=2021_03_04,time=21:20 +'; my @nums = $path =~ m|/day=(\d{4})_(\d{2})_(\d{2}),time=(\d{2}):(\d{2} +)|;

If you do need the $end_of_path variable, there is a more interesting trick:

my $path = '/.snapshots123/yabsm/root/hourly/day=2021_03_04,time=21:20 +'; my ($end_of_path, @nums) = $path =~ m|/(day=(\d{4})_(\d{2})_(\d{2}),time=(\d{2}):(\d{2}))|;

In both of these, I have also used the \d regex char-class escape (see perlre for more) instead of writing out [0-9] repeatedly. The second example uses Perl's list assignment syntax to "peel off" the first value from the returned list, which will contain the contents of each capturing group, in the order in which their left parentheses appear in the expression.

Lastly, for my own testing, I added a few lines to produce some output:

use Data::Dump; dd $end_of_path; dd @nums;

Quick update: The reason that your my @nums = m/([0-9]+)/g =~ $1 if $path =~ m/([^\/]+$)/; does not work is that you have the operands to the =~ operator backwards. Try my @nums = $1 =~ m/([0-9]+)/g if $path =~ m/([^\/]+$)/; instead; the =~ operator is always VALUE =~ PATTERN.


In reply to Re: How can I combine these two regular expressions? by jcb
in thread How can I combine these two regular expressions? by thirtySeven

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.