Roger
Roger

Reputation: 7612

regex get words between braces and quotes (just the words)

I got a string in Ruby like this:

str = "enum('cpu','hdd','storage','nic','display','optical','floppy','other')"

Now i like to return just a array with only the words (not quotes, thats between the round braces (...). The regex below works, buts includes 'enum' which i don't need.

str.scan(/\w+/) 

expected result should be:

{"OPTICAL"=>"optical", "DISPLAY"=>"display", "OTHER"=>"other", "FLOPPY"=>"floppy", "STORAGE"=>"storage", "NIC"=>"nic", "HDD"=>"hdd", "CPU"=>"cpu"}

thanks!

Upvotes: 0

Views: 901

Answers (2)

mgibsonbr
mgibsonbr

Reputation: 22007

I'd suggest using negative lookahead to eliminate words followed by (:

str.scan(/\w+(?!\w|\()/)

Edit: regex updated, now it also excludes \w, so it won't match word prefixes.

Upvotes: 2

Kassym Dorsel
Kassym Dorsel

Reputation: 4843

Based on the output you wanted this will work.

str = "enum('cpu','hdd','storage','nic','display','optical','floppy','other')"
arr = str.scan(/'(\w+)'/)
hs = Hash[arr.map { |e| [e.first.upcase,e.first] }]
p hs #=> {"CPU"=>"cpu", "HDD"=>"hdd", "STORAGE"=>"storage", "NIC"=>"nic", "DISPLAY"=>"display", "OPTICAL"=>"optical", "FLOPPY"=>"floppy", "OTHER"=>"other"}

Upvotes: 1

Related Questions