简体   繁体   中英

Regex combination for parenthesis and commas

I need help with forming the regex for reading a file following the structure:

2050206,"Abella, Jan Vincent P",BSECE,1,Male

How can I ignore the comma inside the double parenthesis? Thank you in advance

Here is an example of how to split on a comma by passing a regex to split .

The negative lookahead (?![^"]*"[^"]*$) prevents a comma being matched if there is only one " ahead in the line.

(?m) turns on MULTILINE mode so that $ matches the end of a line and not the end of the whole string.

public class Example {
    public static void main(String[] args) {
        String string = 
            "2050206,\"Abella, Jan Vincent P\",BSECE,1,Male\n" +
            "2050207,\"Theron, Charlize\",BSECE,2,Female";
        String regex = "(?m),(?![^\"]*\"[^\"]*$)";
        for (String s : string.split(regex)) {
            System.out.println(s);
        }
    }
}

Prints:

2050206
"Abella, Jan Vincent P"
BSECE
1
Male
2050207
"Theron, Charlize"
BSECE
2
Female

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