1

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
1
  • @KennyTM 4,-,3 but if it was "4--3" then 4,-,-3 Commented May 7, 2011 at 16:04

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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));
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.