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

前端 未结 23 2386
我在风中等你
我在风中等你 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条回答
  •  梦毁少年i
    2020-11-21 06:56

    I will post my working versions also(first is really similar to Markus).

    public static String[] splitIncludeDelimeter(String regex, String text){
        List list = new LinkedList<>();
        Matcher matcher = Pattern.compile(regex).matcher(text);
    
        int now, old = 0;
        while(matcher.find()){
            now = matcher.end();
            list.add(text.substring(old, now));
            old = now;
        }
    
        if(list.size() == 0)
            return new String[]{text};
    
        //adding rest of a text as last element
        String finalElement = text.substring(old);
        list.add(finalElement);
    
        return list.toArray(new String[list.size()]);
    }
    

    And here is second solution and its round 50% faster than first one:

    public static String[] splitIncludeDelimeter2(String regex, String text){
        List list = new LinkedList<>();
        Matcher matcher = Pattern.compile(regex).matcher(text);
    
        StringBuffer stringBuffer = new StringBuffer();
        while(matcher.find()){
            matcher.appendReplacement(stringBuffer, matcher.group());
            list.add(stringBuffer.toString());
            stringBuffer.setLength(0); //clear buffer
        }
    
        matcher.appendTail(stringBuffer); ///dodajemy reszte  ciagu
        list.add(stringBuffer.toString());
    
        return list.toArray(new String[list.size()]);
    }
    

提交回复
热议问题