Is there a reduction for a destination of $ 1 ... $ n after matching in ruby

I am looking for a shortcut for the following ruby ​​snippet:

var = 'foo 123  456  789   bar';

var =~ /^foo +(\d+) +(\d+) +(\d+) +bar$/;

first=$1
second=$2
third=$3

It seems to me that there is something like (first, second, third) = ...., but I have no idea how long I could look for it.

+2
source share
3 answers

If you use matchinstead =~, you return an object MatchDatathat has a method capturesthat returns the values ​​matched by the capture groups in the array:

first, second, third = var.match(/.../).captures
+3
source

Another way you can go:

var = 'foo 123  456  789   bar'
/^foo +(?<first>\d+) +(?<second>\d+) +(?<third>\d+) +bar$/ =~ var

This automatically assigns local variables. Note: str =~ regexpdoes not work here. Only regexp =~ str.

, Oniguruma, 1.9
http://www.ruby-doc.org/ruby-1.9/classes/Regexp.html#M001100

+3
str = 'foo 123  456  789   bar'
re  = /^foo +(\d+) +(\d+) +(\d+) +bar$/
p re.match(str).to_a
#=> ["foo 123  456  789   bar", "123", "456", "789"]

_, a, b, c = re.match(str).to_a
p [a,b,c]
#=> ["123", "456", "789"]

Note that it Regex#matchwill return nilif no match is found, but nil.to_areturns an empty array, so the above is safe.

+1
source

All Articles