我在Ruby中得到了一个字符串:
str = "enum('cpu','hdd','storage','nic','display','optical','floppy','other')"
现在我想只返回一个只包含单词的数组(不是引号,在圆括号之间(......)。下面的正则表达式有效,但包括我不需要的'枚举'。
str.scan(/\w+/)
预期结果应为:
{"OPTICAL"=>"optical", "DISPLAY"=>"display", "OTHER"=>"other", "FLOPPY"=>"floppy", "STORAGE"=>"storage", "NIC"=>"nic", "HDD"=>"hdd", "CPU"=>"cpu"}
谢谢!
答案 0 :(得分:2)
答案 1 :(得分:1)
根据您想要的输出,这将有效。
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"}