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

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

    I got here late, but returning to the original question, why not just use lookarounds?

    Pattern p = Pattern.compile("(?<=\\w)(?=\\W)|(?<=\\W)(?=\\w)");
    System.out.println(Arrays.toString(p.split("'ab','cd','eg'")));
    System.out.println(Arrays.toString(p.split("boo:and:foo")));
    

    output:

    [', ab, ',', cd, ',', eg, ']
    [boo, :, and, :, foo]
    

    EDIT: What you see above is what appears on the command line when I run that code, but I now see that it's a bit confusing. It's difficult to keep track of which commas are part of the result and which were added by Arrays.toString(). SO's syntax highlighting isn't helping either. In hopes of getting the highlighting to work with me instead of against me, here's how those arrays would look it I were declaring them in source code:

    { "'", "ab", "','", "cd", "','", "eg", "'" }
    { "boo", ":", "and", ":", "foo" }
    

    I hope that's easier to read. Thanks for the heads-up, @finnw.

提交回复
热议问题