How to split a string, but also keep the delimiters?

前端 未结 23 3017
我在风中等你
我在风中等你 2020-11-21 06:32

I have a multiline string which is delimited by a set of different delimiters:

(Text1)(DelimiterA)(Text2)(DelimiterC)(Text3)(DelimiterB)(Text4)
23条回答
  •  南旧
    南旧 (楼主)
    2020-11-21 06:48

    You want to use lookarounds, and split on zero-width matches. Here are some examples:

    public class SplitNDump {
        static void dump(String[] arr) {
            for (String s : arr) {
                System.out.format("[%s]", s);
            }
            System.out.println();
        }
        public static void main(String[] args) {
            dump("1,234,567,890".split(","));
            // "[1][234][567][890]"
            dump("1,234,567,890".split("(?=,)"));   
            // "[1][,234][,567][,890]"
            dump("1,234,567,890".split("(?<=,)"));  
            // "[1,][234,][567,][890]"
            dump("1,234,567,890".split("(?<=,)|(?=,)"));
            // "[1][,][234][,][567][,][890]"
    
            dump(":a:bb::c:".split("(?=:)|(?<=:)"));
            // "[][:][a][:][bb][:][:][c][:]"
            dump(":a:bb::c:".split("(?=(?!^):)|(?<=:)"));
            // "[:][a][:][bb][:][:][c][:]"
            dump(":::a::::b  b::c:".split("(?=(?!^):)(?

    And yes, that is triply-nested assertion there in the last pattern.

    Related questions

    • Java split is eating my characters.
    • Can you use zero-width matching regex in String split?
    • How do I convert CamelCase into human-readable names in Java?
    • Backreferences in lookbehind

    See also

    • regular-expressions.info/Lookarounds

提交回复
热议问题