我在JavaScript中生成了一系列数组,但需要删除方括号外的所有数字。
现在我知道我需要使用某种形式的Regex,但我不确定如何在这种情况下使用它。
这是我的数组样本:
1 [1,0.031410759078128],2 [2,0.062790519529313],3 [3,0.094108313318514],4 [4,0.1253332335643],5 [5,0.15643446504023]
等
如何删除方括号中的所有数字?
答案 0 :(得分:1)
您需要使用zero-width lookahead assertion。下面的正则表达式字符串将按顺序选择所有直接来自' ['。
的数字。/([0-9]+)(?=\[)+/g
Rexexr.com是一个很好的资源。 http://regexr.com/3e63k
答案 1 :(得分:0)
var stripNumsOutside = function(s) {
var result = "";
var insideBrackets = false;
var curChar;
for (var i = 0;
(i < s.length); i++) {
curChar = s[i];
if (curChar == "[") {
insideBrackets = true;
}
if ((insideBrackets) || (curChar == ",")) {
result += curChar;
};
if (curChar == "]") {
insideBrackets = false;
};
}
return result;
}
console.log(stripNumsOutside("1[1,0.031410759078128],2[2,0.062790519529313],3[3,0.094108313318514],4[4,0.1253332335643],5[5,0.15643446504023]"));