Ruby one-liner to capture regular expression matches

regex, ruby

Solution

string = "the quick brown fox jumps over the lazy dog."

extract_string = string[/fox (.*?) dog/, 1]
# => "jumps over the lazy"

extract_array = string.scan(/the (.*?) fox .*?the (.*?) dog/).first
# => ["quick brown", "lazy"]

This approach will also return `nil` (instead of throwing an error) if no match is found.

extract_string = string[/MISSING_CAT (.*?) dog/, 1]
# => nil

extract_array = string.scan(/the (.*?) MISSING_CAT .*?the (.*?) dog/).first
# => nil

Problem

In Perl, I use the following one line statements to pull matches out of a string via regular expressions and assign them. This one finds a single match and assigns it to a string: ``` my $string = "the quick brown fox jumps over the lazy dog."; my $extractString = ($string =~ m{fox (.*?) dog})[0]; ``` Result: `$extractString == 'jumps over the lazy'` And this one creates an array from multiple matches: ``` my $string = "the quick brown fox jumps over the lazy dog."; my @extractArray = $string =~ m{the (.*?) fox .*?the (.*?) dog}; ``` Result: `@extractArray == ['quick brown', 'lazy']` Is there an equivalent way to create these one-liners in Ruby?

Original source