开发者

Java Split Regex

How can I split the string like

"-3.0*6.7+(5/2)*-0.8--12.98+4^-0.5"

by using regex expression to

-3.0,*,6.7,+,(,5,/,2,),*,-0.8,-,-12.98,+,4,^,-0.开发者_开发知识库5


It is impractical to use regex for this task: you'd better create some sort of tokenizer/lexer to create tokens from your input source. Especially the unary minus signs make this hard for a regex split.

But to answer you question, you could split on the following pattern:

(?=[+*/()^])|(?<=[+*/()^])|(?<=\d-)|(?<=\d)(?=-)

which means:

                # Split on:
(?=[+*/()^])    #   the empty space that has one of: +, *, /, (, ), ^ ahead of it
|               #   OR
(?<=[+*/()^])   #   the empty space that has one of: +, *, /, (, ), ^ before it 
|               #   OR
(?<=\d-)        #   the empty space that has a digit followed by a minus sign before it
|               #   OR
(?<=\d)(?=-)    #   the empty space that has a digit before it and a minus sign ahead of it


I am assuming you ultimately want to evaluate this expression. Here's a code that evaluates arithmetic expressions. It supports the basic arithmetic operators over integers + parenthesis. It should be quite easy to adapt it to support floating point literals.

public class CompactSolver {
  private String input;

  public CompactSolver(String input_) {
   input = input_.trim();
  }

  private char peek(int offset) {
   return offset >= input.length() ? '\0' :
     input.charAt(offset);
  }

  private boolean consumeIf(char c) {
   if (peek(0) != c)
     return false;
   consume(1);
   return true;
  }

  private String consume(int numChars) {
   if (numChars == 0)
     throw new RuntimeException("syntax error");
   String result = input.substring(0, numChars);
   input = input.substring(numChars).trim();
   return result;
  }

  public double eval() {
   double lhs = mul();
   if (consumeIf('+'))
     return lhs + eval();
   else if (consumeIf('-'))
     return lhs - eval();
   return lhs;
  }

  private double mul() {
   double lhs = unary();
   if (consumeIf('*'))
     return lhs * mul();
   else if (consumeIf('/'))
     return lhs / mul();
   return lhs;
  }

  private double unary() {
   if (consumeIf('-'))
     return -unary();

   if (consumeIf('(')) {
     double result = eval();
     if (!consumeIf(')'))
       throw new RuntimeException("Missing ')'");
     return result;
   }

   return literal();
  }

  private double literal() {
   for (int i = 0; true; ++i)
     if (!Character.isDigit(peek(i)))
       return Integer.parseInt(consume(i));
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜