简体   繁体   中英

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?

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

使用此正则表达式(Solaris \\d+)\\s+\\d+/\\d+\\s\\w+\\s\\w+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM