首页 > 解决方案 > Groovy:从字符串数组中获取键值

问题描述

我有一个名为“输出”的变量,它是一个字符串数组,其中包含一个逗号分隔的键值对。使用它的键'ro.product.cpu.abi'来解析它以检索值例如'arm64-v8a'的最佳方法是什么?

       String[] output= androidDetails();
       println("Output is $output")

//prints
//Output is [[ro.product.cpu.abi]: [arm64-v8a], [ro.product.manufacturer]: //[Google], [ro.product.model]: [Pixel 2], [ro.product.name]: [walleye]]

标签: stringgroovy

解决方案


你可以把那个字符串相对容易地变成一张地图,然后你可以从中挑选你想要的。例如

def data = '[[ro.product.cpu.abi]: [arm64-v8a], [ro.product.manufacturer]: [Google], [ro.product.model]: [Pixel 2], [ro.product.name]: [walleye]]'

def parsed = (data =~ /\[([a-z\.]+?)\]\s*:\s*\[(.*?)\]/).iterator().collectEntries{ _, k, v -> [k,v] }

assert parsed['ro.product.cpu.abi'] == 'arm64-v8a'

推荐阅读