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

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

    Another candidate solution using a regex. Retains token order, correctly matches multiple tokens of the same type in a row. The downside is that the regex is kind of nasty.

    package javaapplication2;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class JavaApplication2 {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            String num = "58.5+variable-+98*78/96+a/78.7-3443*12-3";
    
            // Terrifying regex:
            //  (a)|(b)|(c) match a or b or c
            // where
            //   (a) is one or more digits optionally followed by a decimal point
            //       followed by one or more digits: (\d+(\.\d+)?)
            //   (b) is one of the set + * / - occurring once: ([+*/-])
            //   (c) is a sequence of one or more lowercase latin letter: ([a-z]+)
            Pattern tokenPattern = Pattern.compile("(\\d+(\\.\\d+)?)|([+*/-])|([a-z]+)");
            Matcher tokenMatcher = tokenPattern.matcher(num);
    
            List tokens = new ArrayList<>();
    
            while (!tokenMatcher.hitEnd()) {
                if (tokenMatcher.find()) {
                    tokens.add(tokenMatcher.group());
                } else {
                    // report error
                    break;
                }
            }
    
            System.out.println(tokens);
        }
    }
    

    Sample output:

    [58.5, +, variable, -, +, 98, *, 78, /, 96, +, a, /, 78.7, -, 3443, *, 12, -, 3]
    

提交回复
热议问题