java - 将 m.group(1) 转换为字符串数组

标签 java arrays json string pattern-matching

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/

相关文章:

java - 设置布局背景时应用程序崩溃

java - 如何在jbutton中创建一个方法?

arrays - 获取数组而不是字符串

c# - Json 从实体返回额外的值

.net - 如何在 ASP.NET MVC 中将 View 模型转换为 JSON 对象?

javascript - 如何使用 Angular JS 读取 Kickstarter json

java - CheckBox 中的 setChecked 和 setSelected 不起作用

启动jetty服务器时出现java.lang.NullPointerException -> org.apache.maven.InternalErrorException

javascript - 使用数组项作为对象中的键时出现意外 token 错误

java - 识别 Java 中链表中数据条目的类别