使用正则表达式将字符串映射到对象

map a string to an object using regex

出于某些翻译需要,我需要替换具有三个括号的字符串,例如

hello {{{'something'}}} world {{{'something else'}}} ... 

一个包含两个括号和值的字符串

{ 
  value: "hello {{1}} world {{2}}...",
  params: {1: 'something', 2: 'something else', ...}
}

我从这个开始 codepen :

let brutto = "hello {{{'something'}}}} world {{{'something else'}}} ... ";
let regex = /[{]{3}(.+?)[}]{3}/;

let netto = brutto.replace(regex, "{{1}}");
let paramArray = brutto.match(regex).map((e, i) => {return {i: e}});

let result = { value: netto, params: paramArray }
console.log(result);

我明白了

{
    "value": "hello {{1}}} world {{{'something else'}}} ... ",
    "params": [
        {
            "i": "{{{'something'}}}"
        },
        {
            "i": "'something'"
        }
    ]
}

这与期望的结果不太接近...

您可以使用一个函数作为替换,它可以增加一个计数器。

您需要在正则表达式中添加 g 修饰符才能重复匹配。

let brutto = "hello {{{'something'}}}} world {{{'something else'}}} ... ";
let regex = /[{]{3}(.+?)[}]{3}/g;

let counter = 0;
let paramArray = {};
let netto = brutto.replace(regex, (match, g1) => {
  counter++;
  paramArray[counter] = g1;
  return `{{${counter}}}`;
});

result = {value: netto, params: paramArray};
console.log(result);