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

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

    I had a look at the above answers and honestly none of them I find satisfactory. What you want to do is essentially mimic the Perl split functionality. Why Java doesn't allow this and have a join() method somewhere is beyond me but I digress. You don't even need a class for this really. Its just a function. Run this sample program:

    Some of the earlier answers have excessive null-checking, which I recently wrote a response to a question here:

    https://stackoverflow.com/users/18393/cletus

    Anyway, the code:

    public class Split {
        public static List split(String s, String pattern) {
            assert s != null;
            assert pattern != null;
            return split(s, Pattern.compile(pattern));
        }
    
        public static List split(String s, Pattern pattern) {
            assert s != null;
            assert pattern != null;
            Matcher m = pattern.matcher(s);
            List ret = new ArrayList();
            int start = 0;
            while (m.find()) {
                ret.add(s.substring(start, m.start()));
                ret.add(m.group());
                start = m.end();
            }
            ret.add(start >= s.length() ? "" : s.substring(start));
            return ret;
        }
    
        private static void testSplit(String s, String pattern) {
            System.out.printf("Splitting '%s' with pattern '%s'%n", s, pattern);
            List tokens = split(s, pattern);
            System.out.printf("Found %d matches%n", tokens.size());
            int i = 0;
            for (String token : tokens) {
                System.out.printf("  %d/%d: '%s'%n", ++i, tokens.size(), token);
            }
            System.out.println();
        }
    
        public static void main(String args[]) {
            testSplit("abcdefghij", "z"); // "abcdefghij"
            testSplit("abcdefghij", "f"); // "abcde", "f", "ghi"
            testSplit("abcdefghij", "j"); // "abcdefghi", "j", ""
            testSplit("abcdefghij", "a"); // "", "a", "bcdefghij"
            testSplit("abcdefghij", "[bdfh]"); // "a", "b", "c", "d", "e", "f", "g", "h", "ij"
        }
    }
    

提交回复
热议问题