2

I'm trying to capture all parts of a string, but I can't seem to get it right.

The string has this structure: 1+22+33. Numbers with an operator in between. There could be any number of terms.

What I want is ["1+22+33", "1", "+", "22", "+", "33"]

But I get: ["1+22+33", "22", "+", "33"]

I've tried all kinds of regexes, this is the best I've got, but it's obviously wrong.

let re = /(?:(\d+)([+]+))+(\d+)/g;
let s = '1+22+33';
let m;
while (m = re.exec(s))
  console.log(m);

Note: the operators may vary. So in reality I'd look for [+/*-].

revo
  • 43,830
  • 14
  • 67
  • 109
fwend
  • 1,781
  • 2
  • 14
  • 15

3 Answers3

2

You can simply use String#split, like this:

const input = '3+8 - 12'; // I've willingly added some random spaces

console.log(input.split(/\s*(\+|-)\s*/)); // Add as many other operators as needed
Jeto
  • 13,447
  • 2
  • 22
  • 39
1

Just thought of a solution: /(\d+)|([+*/-]+)/g;

revo
  • 43,830
  • 14
  • 67
  • 109
fwend
  • 1,781
  • 2
  • 14
  • 15
  • This regex won't work as it has an unescaped delimiter in it. It will also match 1-+*/23 which I presume isn't really legal? – Nick Apr 08 '18 at 13:10
  • Right that multiplier is wrong. I've noticed that it depends on the regex engine whether or not you need to escape these operators in a class. I'm using this on node.js, and it works fine, but I guess it makes my code less portable. – fwend Apr 08 '18 at 13:27
1

You only have to split on digits:

console.log(
  "1+22+33".split(/(\d+)/).filter(Boolean)
);
revo
  • 43,830
  • 14
  • 67
  • 109