string - 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]]
解决方案
你可以把那个字符串相对容易地变成一张地图,然后你可以从中挑选你想要的。例如
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'
推荐阅读
- javascript - 使用 javascript 或 css 换出屏幕尺寸变化的元素以提高性能速度和减少错误是否更好
- python - 替换 2D numpy 数组中的值
- python - 使用存储在 Pandas 列中的列列表中的指令对多列求和
- android-jetpack-compose - 在 KMM 项目中使用 Compose 主题
- blockchain - 在 Solana 智能合约上调用特定端点
- terraform - 有没有一种简单的方法可以使用 archive_file 打包 node_modules 文件夹和 lambda 处理程序?
- java - Java vs Go 中的整数到字节转换
- pytorch - Loading objects from Google Drive takes a lot more RAM than creating the same objects at runtime in Colab
- c++ - Clarifying the value categories of expressions
- javascript - JavaScript console showing a different console output