gpt4 book ai didi

java - 如何将整数和列表的字符串转换为arrayList

转载 作者:行者123 更新时间:2023-11-29 04:54:06 24 4
gpt4 key购买 nike

我有一种情况,我想将一个字符串转换成一个包含整数和其他数组列表的 ArrayList。 在我的字符串中,我可以将任意数量的单词添加到 ArrayList 对象:

String s = "[2,5,9,8,1,[5,7],9,8,[9,6,9,8],8,9]";

我做了一些工作:

String testdata = "[25,645,[36,65],65]";
ArrayList<Integer> arrayInt = new ArrayList<>();
try (Scanner readFile = new Scanner(testdata)) {
Pattern digitsPattern = Pattern.compile("(\\d+)");
while (readFile.hasNextLine()) {
Matcher m = digitsPattern.matcher(readFile.nextLine());
while (m.find())
arrayInt.add(Integer.valueOf(m.group(1)));
}
}

结果是:

[25, 645, 36, 65, 65]

我想要的是:[25,645,[36,65],65]

最佳答案

删除[],然后使用带有,分隔符的Scanner(或者使用[, ], 作为扫描器的分隔符 - 这个正则表达式应该可以解决 [\\[\\],]+) 的问题。

还要避免 Integer.parseInt 使用返回 intScanner#nextInt

编辑:

如果您愿意接受将包含数字作为浮点类型的列表,例如 doubles,您可以尝试 JSON 序列化/反序列化工具,例如 gson。

String testdata = "[25, 645, [36, 65], 65]";
List fromJson = new Gson().fromJson(testdata, List.class);
System.out.println(fromJson);

输出:[25.0, 645.0, [36.0, 65.0], 65.0]

关于java - 如何将整数和列表的字符串转换为arrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34387199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com