4

I'm trying to split the mathematical strings on maths operators. for example

expression = "7*6+3/2-5*6+(7-2)*5"

I need to tokenize it to produce:

expressionArray = ["7","*","6","+","3","/","2","-","5","*","6"]

I tried finding the solution here and this is what i get

expressoinArray=expression.split("(?<=[-+*/])|(?=[-+*/]")

but looks like this is not fetching the desired result for expression.

Vega
  • 27,856
  • 27
  • 95
  • 103
min2bro
  • 554
  • 2
  • 9
  • 19
  • Aren't you missing a `+` between `"6","3"` – epascarello Jun 11 '13 at 18:25
  • 1
    What is with expressions like 1--2? – Thomas Junk Jun 11 '13 at 18:27
  • 2
    Is `String1` a type of input, or the desired output? – JJJ Jun 11 '13 at 18:28
  • 3
    This question makes little sense. The `String` isn't a string, and `String1` is an Array of some, but not all, of the tokens used to assigned to `String`. The value passed to `.split()` is a string sequence of characters seemingly unrelated to anything, though it looks like it could be intended to operate as a regex. And the desired input and output are unclear. –  Jun 11 '13 at 18:32
  • You say it isn't the desired result, but you also don't say what the desired result is. – Alex W Jun 11 '13 at 18:45
  • I think this question is valid and needs to be reopened. One use case for this when converting postfix mathematical notation to prefix using shant yard algorithm. – Mosaaleb Dec 16 '19 at 00:32

3 Answers3

8

jsfiddle

var expression = "7.2*6+3/2-5*6+(7-2)*5";
var copy = expression;

expression = expression.replace(/[0-9]+/g, "#").replace(/[\(|\|\.)]/g, "");
var numbers = copy.split(/[^0-9\.]+/);
var operators = expression.split("#").filter(function(n){return n});
var result = [];

for(i = 0; i < numbers.length; i++){
     result.push(numbers[i]);
     if (i < operators.length) result.push(operators[i]);
}

console.log(result);
Gabe
  • 49,577
  • 28
  • 142
  • 181
7

EDIT:

This works like the accepted answer and as a bonus won't fail due to filter() in IE8 and below:

var expression = "7.2*6+3/2-5*6+(7-2)*5";
var splitUp = expression.match(/[^\d()]+|[\d.]+/g);
document.body.innerHTML = splitUp;

http://jsfiddle.net/smAPk/

Alex W
  • 37,233
  • 13
  • 109
  • 109
  • 1
    Your solution is elegant, but both you and the accepted answer have a bug. the following expression `5 + -1` returns `['5', '+ -', '1']`, which doesn't make much sense.. You still got my upvote though ;) – Ronen Ness Aug 31 '16 at 06:17
1

First of all, if you want to use a regular expression with split() you have to create it first:

var expr = new RegExp("(?<=[-+*/])|(?=[-+*/])")  
// note: you missed a ) at the end

Sadly, the RegExp engine in most browsers doesn't support lookbehinds, so it won't work anyway. You have to do this in a loop.

lqc
  • 7,434
  • 1
  • 25
  • 25