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

前端 未结 23 2286
我在风中等你
我在风中等你 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:42

    Fast answer: use non physical bounds like \b to split. I will try and experiment to see if it works (used that in PHP and JS).

    It is possible, and kind of work, but might split too much. Actually, it depends on the string you want to split and the result you need. Give more details, we will help you better.

    Another way is to do your own split, capturing the delimiter (supposing it is variable) and adding it afterward to the result.

    My quick test:

    String str = "'ab','cd','eg'";
    String[] stra = str.split("\\b");
    for (String s : stra) System.out.print(s + "|");
    System.out.println();
    

    Result:

    '|ab|','|cd|','|eg|'|
    

    A bit too much... :-)

提交回复
热议问题