How can tokenize this string in java?

后端 未结 9 1082
你的背包
你的背包 2021-01-14 17:32

How can I split these simple mathematical expressions into seperate strings?

I know that I basically want to use the regular expression: \"[0-9]+|[*+-^()]\"

9条回答
  •  失恋的感觉
    2021-01-14 17:37

    Here's a short Java program that tokenizes such strings. If you're looking for evaluation of expression I can (shamelessly) point you at this post: An Arithemetic Expressions Solver in 64 Lines

      import java.util.ArrayList;
      import java.util.List;
    
      public class Tokenizer {
         private String input;
    
         public Tokenizer(String input_) { input = input_.trim(); }
    
         private char peek(int i) {
            return i >= input.length() ? '\0' : input.charAt(i);
         }
    
         private String consume(String... arr) {
            for(String s : arr)
               if(input.startsWith(s))
                  return consume(s.length());
            return null;
         }
    
         private String consume(int numChars) {
            String result = input.substring(0, numChars);
            input = input.substring(numChars).trim();
            return result;
         }
    
         private String literal() {
            for (int i = 0; true; ++i)
               if (!Character.isDigit(peek(i)))
                  return consume(i);
         }
    
         public List tokenize() {
            List res = new ArrayList();
            if(input.isEmpty())
               return res;
    
            while(true) {
               res.add(literal());
               if(input.isEmpty())
                  return res;
    
               String s = consume("+", "-", "/", "*", "^");
               if(s == null)
                  throw new RuntimeException("Syntax error " + input);
               res.add(s);
            }
         }
    
         public static void main(String[] args) {
            Tokenizer t = new Tokenizer("578+223-5^2");
            System.out.println(t.tokenize());
         }   
      }
    

提交回复
热议问题