m.group(1)
的内容包含使用正则表达式 (regex) 从 JSON/URL 提取的 URL 列表,我需要将它们传输到 ArrayList
。
我可以打印出所有行
System.out.println(googleCs.get(0));
但是,以下给出了Index 1 out ofbound for length 1 error
System.out.println(googleCs.get(1));
我尝试使用字符串和数组并在 "\n"
(新行)上进行拆分,如下所示:
String myStringGoogle = m.group(1);
String[] b = myStringGoogle.split("\n");
但是我遇到了完全相同的问题
private static void matchPattern(
String inputLine, Pattern pattern, BufferedWriter bw
) throws IOException {
Matcher m = pattern.matcher(inputLine);
while (m.find()) {
ArrayList<String> googleCs = new ArrayList<String>();
googleCs.add(m.group(1));
System.out.println(googleCs.get(0));
}
}
最佳答案
将 googleCs
的声明和初始化移至循环之前 - 就像在循环的每次迭代中丢弃 List
一样。填充List
(并编程到List
接口(interface),而不是ArrayList
具体类型)。循环后打印。就像,
private static void matchPattern(String inputLine, Pattern pattern, BufferedWriter bw)
throws IOException
{
Matcher m = pattern.matcher(inputLine);
List<String> googleCs = new ArrayList<>();
while (m.find()) {
googleCs.add(m.group(1));
}
System.out.println(googleCs);
}
关于java - 将 m.group(1) 转换为字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57798650/