我有像“1 + 2 - 3 + 10
”这样的字符串。
我想将其拆分为 "1", "+2", "-3", "+10"
。
这是我的代码。
var expression = "1 + 2 - 3 + 10";
expression = expression.replace(/\s+/g, '');
let fields = expression.split(/([+-]\d+)/g);
console.log(fields);
结果是
["1", "+2", "", "-3", "", "+10", ""]
如何使结果["1", "+2", "-3", "+10"]
?
答案 0 :(得分:1)
你的正则表达式需要一组
/([+-]\d+)/
^ ^ group
包含在结果集中。
作为结果,您在每次后续迭代中都会得到两部分,即组中的前部分和组本身。
"1" first find
"+2" group as separator for splitting, included to result set
"" second find, empty because of the found next separator
"-3" second separator/group
"" third part without separator
"+10" third separator
"" rest part between separator and end of string
您可以使用运算符的正向预测进行拆分。
const
string = '1 + 2 - 3 + 10',
result = string.replace(/\s+/g, '').split(/(?=[+-])/);
console.log(result);
答案 1 :(得分:0)
我将通过首先去除所有空格,然后使用 match()
和正则表达式模式 [/*+-]?\d+
来处理这个问题,它将匹配所有数字,并带有一个可选的前导运算符(第一个术语不存在) .
var input = "1 + 2 - 3 + 10";
var matches = input.replace(/\s+/g, '').match(/[/*+-]?\d+/g);
console.log(matches);