我正在尝试捕获字符串的所有部分,但似乎无法正确处理。
字符串具有以下结构: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);
注意:操作员可能会有所不同。所以实际上我会寻找[+/*-]
。
您可以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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句