2011-05-07 95 views
1

我怎样才能分割字符串像Java的正则表达式分割

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

通过使用正则表达式表达

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

如何分割'“4-3”'? – kennytm 2011-05-07 13:04:13

+0

@KennyTM 4, - ,3但如果它是“4-3”,那么4, - , - 3 – 2011-05-07 16:04:00

回答

2

这是不切实际的使用正则表达式完成这个任务:你最好建立某种形式的标记器/词法分析器从输入源创建标记。特别是一元减号使得正则表达式难以分割。

但是,为了回答你的问题,你可能分裂以下模式:

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

这意味着:

   # 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 
0

我假设你最终要计算这个表达式。这是一个评估算术表达式的代码。它通过整数+括号支持基本的算术运算符。使它适应浮点文字应该很容易。

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