您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

仅将文件中的特定文本添加到数组列表,第2部分-Java

仅将文件中的特定文本添加到数组列表,第2部分-Java

最好使用正则表达式提取行上的数字,而不要尝试跟踪/猜测它(请参见下文)。

这是对代码的一种经过测试的重新创建,因为您引用了一些您未提供的类…但这有望对您有所帮助:

public static String getMatch(final String pattern, final String content) {
    Pattern r = Pattern.compile(pattern);
    Matcher m = r.matcher(content);

    if (m.find()) {
        return m.group(1);
    } else {
        return "";
    }
}

public static void load(String fileName) throws FileNotFoundException {

    List<String> places = new ArrayList<String>();
    List<String> names = new ArrayList<String>();
    List<String> nameDetails = new ArrayList<String>();

    BufferedReader br = new BufferedReader(new FileReader(fileName));

    String text;
    String lastName = "";

    try {

        while ((text = br.readLine()) != null) {
            // extract num from start of line or empty if none..
            String num = getMatch("^([0-9]+)\\.", text);

            if (text.contains("Place:")) {
                text = text.replaceAll("Place:", "");
                places.add(text);
            } else if (text.contains(num + ". Name:")) {
                text = text.replaceAll(num + ". Name:", "");
                names.add(text);
                lastName = text;
            } else if (text.contains(num + ". Name detail:")) {
                text = text.replaceAll(num + ". Name detail:", "");
                nameDetails.add(lastName + " had " + text);
            }
        }
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    }

    System.out.println("Places:" + places);
    System.out.println("Names:" + names);
    System.out.println("Name Details:" + nameDetails);
}
java 2022/1/1 18:32:48 有473人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶