fwend
fwend

Reputation: 1853

regex capturing with repeating pattern

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 [+/*-].

Upvotes: 2

Views: 186

Answers (3)

revo
revo

Reputation: 48711

You only have to split on digits:

console.log(
  "1+22+33".split(/(\d+)/).filter(Boolean)
);

Upvotes: 1

Jeto
Jeto

Reputation: 14927

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

Upvotes: 2

fwend
fwend

Reputation: 1853

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

Upvotes: 1

Related Questions