How to split a string on multiple single‑character delimiters (and keep them) in Java

1 Answer

0 votes
import java.util.List;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SplitKeepDelims {

    /**
     * Splits a string on multiple single-character delimiters
     * and keeps the delimiters in the result.
     */
    public static List<String> splitKeepDelims(String s, String delimiters) {
        List<String> result = new ArrayList<>();

        // Build regex: e.g. ",;|" → "([,;|])"
        String regex = "([" + Pattern.quote(delimiters) + "])";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(s);

        int lastEnd = 0;

        while (matcher.find()) {
            // Add text before delimiter
            if (matcher.start() > lastEnd) {
                result.add(s.substring(lastEnd, matcher.start()));
            }

            // Add the delimiter itself
            result.add(matcher.group());

            lastEnd = matcher.end();
        }

        // Add remaining text after last delimiter
        if (lastEnd < s.length()) {
            result.add(s.substring(lastEnd));
        }

        return result;
    }

    public static void main(String[] args) {
        String input = "aa,bbb;cccc|ddddd";
        List<String> parts = splitKeepDelims(input, ",;|");

        for (String p : parts) {
            System.out.print("[" + p + "] ");
        }
    }
}



/*
run:

[aa] [,] [bbb] [;] [cccc] [|] [ddddd] 

*/

 



answered Mar 9 by avibootz

Related questions

...