简体   繁体   中英

Parsing using Pattern in Java

I want to Parse the lines of a file Using parsingMethod

test.csv

 Frank George,Henry,Mary / New York,123456
,Beta Charli,"Delta,Delta Echo
", 25/11/1964, 15/12/1964,"40,000,000.00",0.0975,2,"King, Lincoln ",Alpha

This is the way i read line

 public static void main(String[] args) throws Exception {


        File file = new File("C:\\Users\\test.csv");
        BufferedReader reader = new BufferedReader(new FileReader(file));   
        String line2;
        while ((line2= reader.readLine()) !=null) {
            String[] tab = parsingMethod(line2, ",");
            for (String i : tab) {
                System.out.println( i );
            }
        }


    }

    public static String[] parsingMethod(String line,String parser) {

        List<String> liste = new LinkedList<String>();
        String patternString ="(([^\"][^"+parser+ "]*)|\"([^\"]*)\")" +parser+"?";
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher =pattern.matcher(line);

        while (matcher.find()) {
            if(matcher.group(2) != null){
                liste.add(matcher.group(2).replace("\n","").trim());
            }else if(matcher.group(3) != null){
                liste.add(matcher.group(3).replace("\n","").trim());
            }       
        }

        String[] result = new String[liste.size()];
        return liste.toArray(result);
    }
}

Output :

Frank George
Henry
Mary / New York
123456

Beta Charli
Delta
Delta Echo
"
25/11/1964
15/12/1964
40,000,000.00
0.0975
2
King
Lincoln
"
Alpha
Delta
Delta Echo

I want to remove this " , Can any one help me to improve my Pattern.


Expected output

Frank George
Henry
Mary / New York
123456
Beta Charli
Delta
Delta Echo
25/11/1964
15/12/1964
40,000,000.00
0.0975
2
King
Lincoln
Alpha
Delta
Delta Echo

Output for line 3

25/11/1964
15/12/1964

40
000
000.00


0.0975
2

King
Lincoln

Your code didn't compile properly but that was caused by some of the " not being escaped.

But this should do the trick:

String patternString = "(?:^.,|)([^\"]*?|\".*?\")(?:,|$)";
Pattern pattern = Pattern.compile(patternString, Pattern.MULTILINE);

(?:^.,|) is a non capturing group that matches a single character at the start of the line

([^\\"]*?|\\".*?\\") is a capturing group that either matches everything but " OR anything in between " "

(?:,|$) is a non capturing group that matches a end of the line or a comma.

Note: ^ and $ only work as stated when the pattern is compiled with the Pattern.MULTILINE flag

I can't reproduce your result but I'm thinking maybe you want to leave the quotes out of the second captured group, like this:

"(([^\"][^"+parser+ "]*)|\"([^\"]*))\"" +parser+"?"

Edit: Sorry, this won't work. Maybe you want to let any number of ^\\" in the first group as well, like this: (([^,\\"]*)|\\"([^\\"]*)\\"),?

As i can see the lines are related so try this:

    public static void main(String[] args) throws Exception {

        File file = new File("C:\\Users\\test.csv");
        BufferedReader reader = new BufferedReader(new FileReader(file));
        StringBuilder line = new StringBuilder();
        String lineRead;
        while ((lineRead = reader.readLine()) != null) {
            line.append(lineRead);
        }
        String[] tab = parsingMethod(line.toString());
        for (String i : tab) {
            System.out.println(i);
        }


    }

    public static String[] parsingMethod(String line) {

        List<String> liste = new LinkedList<String>();
        String patternString = "(([^\"][^,]*)|\"([^\"]*)\"),?";
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(line);

        while (matcher.find()) {
            if (matcher.group(2) != null) {
                liste.add(matcher.group(2).replace("\n", "").trim());
            } else if (matcher.group(3) != null) {
                liste.add(matcher.group(3).replace("\n", "").trim());
            }
        }

        String[] result = new String[liste.size()];
        return liste.toArray(result);
    }

Ouput:

Frank George
Henry
Mary / New York
123456
Beta Charli
Delta,Delta Echo
25/11/1964
15/12/1964
40,000,000.00
0.0975
2
King, Lincoln
Alpha

as Delta, Delta Echo is in a quotation this should appear in the same line ! like as King, Lincoln

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM