Perl assign regex match groups to variables

grouping, perl, regex

Solution

That should be (assuming your string is stored in '`$string`'):

my ($var1, $var2) = $string =~ /_(\d+)_(\d+)/s; 

The idea is to grab numbers until you get a non-number character: here '`_`'.

Each capturing group is then assign to their respective variable.

As mentioned in this question (and in the comments below by Kaoru):

`\d` can indeed match more than 10 different characters, if applied to Unicode strings.

So you can use instead:

my ($var1, $var2) = $string =~ /_([0-9]+)_([0-9]+)/s; 

Problem

I'have a string in a following format: `_num1_num2`. I need to assign `num1` and `num2` values to some variables. My regex is `(\d+)` and it shows me the correct match groups on Rubular.com, but I don't know how to assign these match groups to some variables. Can anybody help me? Thanks in adv.

Original source

Related problems