Ruby Regex Captures Oneliner

Surely this post is nothing new for experienced ruby developpers, but I found it so handy, that I thought it deserved a post of its own though. The problem is :

How do I match and assign captures from a regex in a single line of code ?

Here is the idea :

1
2
3
4
5
6
> brand, item = /([^,]*), (.*)/.match("APPLE, ipad").captures
=> ["APPLE", "ipad"]
> brand
=> "APPLE"
> item
=> "ipad"

There are a few variations around this, like grouping some catpures in an array :

1
2
3
4
5
6
> brand, *details = /([^,]*), ([^:]*): (.*)/.match("APPLE, ipad: iOs").captures
=> ["APPLE", "ipad", "iOs"]
> brand
=> "APPLE"
> details
=> ["ipad", "iOs"]

Or to ignore some capture, we could shorten skip some captures :

1
2
3
4
5
6
> item, details = /([^,]*), ([^:]*): (.*)/.match("APPLE, ipad: iOs")[2..-1]
=> ["ipad", "iOs"]
> item
=> "ipad"
> details
=> "iOs"

But this only works for first or last captures, when this is not the case, one can also use the functional programming ‘_’ sink convention :

1
2
3
4
5
6
> brand, _, details = /([^,]*), ([^:]*): (.*)/.match("APPLE, ipad: iOs").captures
=> ["APPLE", "ipad", "iOs"]
> brand
=> "APPLE"
> details
=> "iOs"

One can even use ‘_’ multiple times on the same match

1
2
3
4
> _, _, details = /([^,]*), ([^:]*): (.*)/.match("APPLE, ipad: iOs").captures
=> ["APPLE", "ipad", "iOs"]
> details
=> "iOs"

I hope this helps.

Comments