Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Re: How can I combine these two regular expressions?

by jcb (Parson)
on Mar 05, 2021 at 03:41 UTC ( [id://11129142] : note . print w/replies, xml ) Need Help??

in reply to How can I combine these two regular expressions?

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.