Sirch
Sirch

Reputation: 417

Ruby Regex Match Multiple variable from a single string

Fairly new to ruby. I'm trying to parse a string and assign several variables with a regex.

I've consulted the docs, Googled a bit, and pretty sure that the following should work.

@operating_system, @os_update, @os_arch = @version_line[0].match(
        /(Solaris \d+)\s+\d+\/\d+\ss\d+[sx]_u(\d+)\wos_\d+\w+\s+(\w+)$/
        )

Where @version_line = [" Oracle Solaris 10 9/10 s10x_u9wos_14a X86\n"]

But all that happens is my first variable, @operating_system is assigned Solaris 10 9/10 s10x_u9wos_14a X86

Am I trying to do it the wrong way?

Upvotes: 0

Views: 576

Answers (2)

Thomas
Thomas

Reputation: 182083

Actually, match returns a MatchData object, which happens to have a to_s method that produces the string you see.

To get all matched capture groups as an array, use the captures method:

@operating_system, @os_update, @os_arch = @version_line[0].match(
        /(Solaris \d+)\s+\d+\/\d+\ss\d+[sx]_u(\d+)\wos_\d+\w+\s+(\w+)$/
        ).captures

Upvotes: 1

burning_LEGION
burning_LEGION

Reputation: 13460

use this regex (Solaris \d+)\s+\d+/\d+\s\w+\s\w+

Upvotes: 0

Related Questions