我有一个带有此模式的字符串:field1:"with space","tag1","tag2" field2:"f1",f2" FooBar1 FooBar2
如何提取字段并将其转换为属性为hash[:field1] = ["with space", "tag1", "tag2"]
答案 0 :(得分:1)
此问题的答案和难点取决于字符串中的字符串包含的字符类型。对于当前字符串,这有效:
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
表示捕获一个单词后跟一个:,然后引号之间的所有数据后跟一个空格。