Search code examples
javascriptregexarithmetic-expressions

Split an arithmetic expression with a regex


I want to split an expression like -1*-0.8/5-5 into [ '-1', '*', '-0.8', '/', '5', '-', '5' ]

[ '-1', '*', '-0.8', '/', '5-5' ] This is what I'm getting right now with expression.split(/([*/])/g);

Any suggestions on this?


Solution

  • Here is a solution. It correctly detects +, -, /, * and accept the use of whitespaces:

    ([*\/]|\b\s*-|\b\s*\+)
    

    var expression = "-1*-0.8/5-5";
    console.log(expression.split(/([*\/]|\b\s*-|\b\s*\+)/g));

    ##Demo on regex101


    From Wiktor's comment, here is an improvement accepting parenthesis

    var expression = "-1 * -0.8 / (5 - 5)";
    console.log(expression.split(/([*\/()]|\b\s*[-+])/g));

    ##Demo on regex101