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

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

    Here's a groovy version based on some of the code above, in case it helps. It's short, anyway. Conditionally includes the head and tail (if they are not empty). The last part is a demo/test case.

    List splitWithTokens(str, pat) {
        def tokens=[]
        def lastMatch=0
        def m = str=~pat
        while (m.find()) {
          if (m.start() > 0) tokens << str[lastMatch..this is the title',/<[^>]+>/],
     ['beforethis is the titleafter',/<[^>]+>/]
    ].each { 
       println splitWithTokens(*it)
    }
    

提交回复
热议问题