我有一个带有这种模式的字符串:field1:"with space","tag1","tag2" field2:"f1",f2" FooBar1 FooBar2
我如何提取字段并将它们转换为具有属性的哈希hash[:field1] = ["with space", "tag1", "tag2"]
这个问题的答案和难度取决于字符串里面的字符串包含什么样的字符。对于当前字符串,这有效:
s = 'field1:"with space","tag1","tag2" field2:"f1","f2" FooBar1 FooBar2'
split_string = s.scan(/(\w+):(".*?")\s/)
split_string.map! do |key, string|
[key, string.delete('"').split(',')]
end
p Hash[split_string]
# => {"field1"=>["with space", "tag1", "tag2"], "field2"=>["f1", "f2"]}
正则表达式/(\w+):(".*?")\s
意味着捕获一个单词后跟一个:,然后是引号之间的所有数据,后跟一个空格。