Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

regex - Java: splitting a comma-separated string but ignoring commas in parentheses

I have a string like this:

one,two,3,(4,five),six,(seven),(8,9,ten),eleven,(twelve,13,14,fifteen)

the above string should split into:

one
two
3
(4,five)
six
(seven)
(8,9,ten)
eleven
(twelve,13,14,fifteen)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The simplest solution to my opinion is to process the input string char-by-char:

public static List<String> split(String input) {
    int nParens = 0;
    int start = 0;
    List<String> result = new ArrayList<>();
    for(int i=0; i<input.length(); i++) {
        switch(input.charAt(i)) {
        case ',':
            if(nParens == 0) {
                result.add(input.substring(start, i));
                start = i+1;
            }
            break;
        case '(':
            nParens++;
            break;
        case ')':
            nParens--;
            if(nParens < 0) 
                throw new IllegalArgumentException("Unbalanced parenthesis at offset #"+i);
            break;
        }
    }
    if(nParens > 0)
        throw new IllegalArgumentException("Missing closing parenthesis");
    result.add(input.substring(start));
    return result;
}

Example:

split("one,two,3,(4,five),six,(seven),(8,9,ten),eleven,(twelve,13,14,fifteen)") ->
[one, two, 3, (4,five), six, (seven), (8,9,ten), eleven, (twelve,13,14,fifteen)]

As a free bonus, this solution also counts nested parentheses if necessary:

split("one,two,3,(4,(five,six),seven),eight") ->
[one, two, 3, (4,(five,six),seven), eight]

Also it checks whether parentheses are balanced (every open parenthesis has the corresponding closing one).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...