Regex : Split on comma , but exclude commas within parentheses and quotes(Both single & Double)

前端 未结 3 964
甜味超标
甜味超标 2021-01-15 13:55

I have one string

5,(5,5),C\'A,B\',\'A,B\',\',B\',\'A,\',\"A,B\",C\"A,B\" 

I want to split it on comma but need to exclude commas within pa

3条回答
  •  一整个雨季
    2021-01-15 14:13

    You can use this regex:

    String input = "5,(5,5),C'A,B','A,B',',B','A,',\"A,B\",C\"A,B\"";
    String[] toks = input.split( 
                    ",(?=(([^']*'){2})*[^']*$)(?=(([^\"]*\"){2})*[^\"]*$)(?![^()]*\\))" );
    for (String tok: toks)
        System.out.printf("<%s>%n", tok);
    

    Output:

    <5>
    <(5,5)>
    
    <'A,B'>
    <',B'>
    <'A,'>
    <"A,B">
    
    

    Explanation:

    ,                         # Match literal comma
    (?=(([^']*'){2})*[^']*$)  # Lookahead to ensure comma is followed by even number of '
    (?=(([^"]*"){2})*[^"]*$)  # Lookahead to ensure comma is followed by even number of "
    (?![^()]*\\))             # Negative lookahead to ensure ) is not followed by matching
                              # all non [()] characters in between
    

提交回复
热议问题