我在Ruby中得到一个字符串,如下所示:
str = "enum('cpu','hdd','storage','nic','display','optical','floppy','other')"现在我只想返回一个只包含单词(而不是引号,在圆括号(...)之间)的数组。下面的正则表达式可以工作,但是包含了我不需要的'enum‘。
str.scan(/\w+/) 预期结果应为:
{"OPTICAL"=>"optical", "DISPLAY"=>"display", "OTHER"=>"other", "FLOPPY"=>"floppy", "STORAGE"=>"storage", "NIC"=>"nic", "HDD"=>"hdd", "CPU"=>"cpu"}谢谢!
发布于 2012-03-20 01:55:05
我建议先使用negative lookahead消除单词,然后使用(
str.scan(/\w+(?!\w|\()/)编辑:正则表达式更新了,现在它也排除了\w,所以它不会匹配单词前缀。
发布于 2012-03-20 03:52:54
根据您想要的输出,这将会起作用。
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"}https://stackoverflow.com/questions/9775224
复制相似问题