从字符串中获取元素数组并查找值

Get array of elements from a string and look up values

我有一个来自数据库的计算字符串,例如:

var calc = "{a}+{b}==2"

并且我想使用“{}”提取所有元素,以便我可以从数据库中查找它们的值。 最快 的方法是什么,所以我最终得到一个有序数组,我可以查找它,并将值替换回字符串中。

我考虑过:

 - For loop, looking for { then finding the next }
 - Split with a map
 - IndexOf

使用正则表达式

 var exp = /{([^}]+)}/g ,index;
  while(index = exp.exec("{a}+{b}==2")) {
    console.log(index[1]);
  }

Demo

不确定这是否是 "fastest" 方式,但您应该考虑使用正则表达式。

类似于:

var calc = "{a}+{b}==2";
var re = /{([^}]+)}/g;
var res;
var result = [];
while (res = re.exec(calc))
{
    result.push(res[1]);
}
console.log(result);

您的正则表达式可能需要根据 {} 表达式的实际定义(基于允许的字符、引号等)进行优化。

收到返回的值后,您可以使用 replace 替换值。

var values = {a: 1, b: 3};
var replaced = calc.replace(re,function(match,name) { return values[name]; });
console.log(replaced);

注意:如果您打算将其发送给 eval 或类似的人,请 非常 小心。

首先想到的是正则表达式,但在 O(n) 时间内实现此工作的另一种方法可能是;

function getDatas(s){
  var dataOn = false;
  return Array.prototype.reduce.call(s,(d,c) => dataOn ? c !== "}" ? (d[d.length-1] += c,d)
                                                                   : (dataOn = false, d)
                                                       : c === "{" ? (dataOn = true, d.push(""),d)
                                                                   : d, []);
  
}

var calc = "{a}+{b}+{colorSpace}==2",
  result = getDatas(calc);
console.log(result);

出于好奇,我在 JSBen 上做了一些测试,看起来 @jcaron 的正则表达式确实非常有效。您可以使用任何其他想法扩展这些测试,例如 indexOffor 循环。