有没有快速正则表达式方法或类似方法可以将字符串解析为双花括号中的not位(我们称之为"静态")和双花括号中的are位(我们称之为"动态")?
例如,输入:
Lorem {{ipsum dolor sit}} amet, {consectetur} adipiscing {{elit}}.
所需输出:
[
{
type: "static",
value: "Lorem "
},
{
type: "dynamic",
value: "ipsum dolor sit"
},
{
type: "static",
value: " amet, {consectetur} adipiscing "
},
{
type: "dynamic",
value: "elit"
},
{
type: "static",
value: "."
},
]
到目前为止,我最好的try 是使用/\{*([^{}]+)\}*/g
作为正则表达式,并使用while
和exec
循环,但它错误地将any个花括号标识为动态值,如下所示:
function templateParser(string) {
const re = /\{*([^{}]+)\}*/g;
const output = [];
while (true) {
const match = re.exec(string);
if (!match) {
break;
}
const [templateItem, templateKey] = match;
output.push({
type: templateItem === templateKey ? "static" : "dynamic",
value: templateItem === templateKey ? templateItem : templateKey
});
}
return output;
}
console.log(
templateParser(
"Lorem {{ipsum dolor sit}} amet, {consectetur} adipiscing {{elit}}."
)
);