用重复模式捕获正则表达式

时间:2018-04-08 12:48:58

标签: javascript regex

我正在尝试捕获字符串的所有部分,但我似乎无法正确使用它。

字符串具有以下结构:1+22+33。中间有操作员的数字。可以有任意数量的术语。

我想要的是["1+22+33", "1", "+", "22", "+", "33"]

但我明白了:["1+22+33", "22", "+", "33"]

我尝试过各种各样的正则表达式,这是我得到的最好的,但显然是错的。

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

注意:运营商可能会有所不同。所以实际上我会寻找[+/*-]

3 个答案:

答案 0 :(得分:2)

您只需使用String#split,就像这样:

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

答案 1 :(得分:1)

想到了一个解决方案:/(\d+)|([+*/-]+)/g;

答案 2 :(得分:1)

您只需split数字:

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