Adding only specific text from a file to an array list, part 2 - Java

前端 未结 2 883
名媛妹妹
名媛妹妹 2021-01-29 10:06

I hope I can have some great suggestion how I can solve this here:

I have this text file with places and names - name detail indicates the place(s) that the person has v

2条回答
  •  无人及你
    2021-01-29 11:00

    It might be better to use a regular expression to extract the digit on the line instead of trying to track/guess it (see below).

    This is a tested recreation of your code since you reference some classes that you didn't provide...but this should hopefully help:

    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 places = new ArrayList();
        List names = new ArrayList();
        List nameDetails = new ArrayList();
    
        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);
    }
    

提交回复
热议问题