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

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

    Tweaked Pattern.split() to include matched pattern to the list

    Added

    // add match to the list
            matchList.add(input.subSequence(start, end).toString());
    

    Full source

    public static String[] inclusiveSplit(String input, String re, int limit) {
        int index = 0;
        boolean matchLimited = limit > 0;
        ArrayList matchList = new ArrayList();
    
        Pattern pattern = Pattern.compile(re);
        Matcher m = pattern.matcher(input);
    
        // Add segments before each match found
        while (m.find()) {
            int end = m.end();
            if (!matchLimited || matchList.size() < limit - 1) {
                int start = m.start();
                String match = input.subSequence(index, start).toString();
                matchList.add(match);
                // add match to the list
                matchList.add(input.subSequence(start, end).toString());
                index = end;
            } else if (matchList.size() == limit - 1) { // last one
                String match = input.subSequence(index, input.length())
                        .toString();
                matchList.add(match);
                index = end;
            }
        }
    
        // If no match was found, return this
        if (index == 0)
            return new String[] { input.toString() };
    
        // Add remaining segment
        if (!matchLimited || matchList.size() < limit)
            matchList.add(input.subSequence(index, input.length()).toString());
    
        // Construct result
        int resultSize = matchList.size();
        if (limit == 0)
            while (resultSize > 0 && matchList.get(resultSize - 1).equals(""))
                resultSize--;
        String[] result = new String[resultSize];
        return matchList.subList(0, resultSize).toArray(result);
    }
    

提交回复
热议问题