Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl assign regex match groups to variables

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.

like image 566
kulan Avatar asked May 31 '14 06:05

kulan


2 Answers

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; 
like image 73
VonC Avatar answered Sep 28 '22 03:09

VonC


Using the g-modifier also allows you to do away with the the grouping parenthesis:

my ($five, $sixty) = '_5_60' =~ /\d+/g;

This allows any separation of integers but it doesn't verify the input format.

like image 35
Richard RP Avatar answered Sep 28 '22 01:09

Richard RP