You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Web应用模板字符串中提取[[与]]间的变量并转为数组?

提取模板中[[variable]]格式变量到数组的实现方案

针对你需要提取模板中[[variable]]格式变量的需求,最直接高效的方式是使用正则表达式全局匹配,以下是主流Web开发场景的实现示例:

JavaScript 实现(前端/Node.js)

// 示例模板内容
const template = `Hi [[recipient]],

Here are your login credentials:

Username: [[username]]

Password: [[password]]`;

// 定义匹配规则:捕获[[和]]之间的内容
const variableRegex = /\[\[([^\]]+)\]\]/g;
const variables = [];
let matchResult;

// 遍历所有匹配项
while ((matchResult = variableRegex.exec(template)) !== null) {
  // matchResult[1]是捕获到的变量名
  variables.push(matchResult[1]);
}

// 可选:去重(避免同一变量多次出现)
const uniqueVariables = [...new Set(variables)];

console.log(uniqueVariables); // 输出: ['recipient', 'username', 'password']

Python 实现(后端场景)

import re

template = """Hi [[recipient]],

Here are your login credentials:

Username: [[username]]

Password: [[password]]"""

# 匹配规则与JS一致
pattern = r'\[\[([^\]]+)\]\]'
# 直接获取所有匹配的变量名
variables = re.findall(pattern, template)

# 可选:去重
unique_variables = list(set(variables))

print(unique_variables) # 输出: ['recipient', 'username', 'password']

关键说明

  1. 正则逻辑:/\[\[([^\]]+)\]\]/g 中:
    • \[\[ 和 \]\] 匹配模板中的字面量[[和]]
    • ([^\]]+) 捕获一个或多个非]的字符(即变量名)
    • g 标记开启全局匹配,确保遍历所有符合格式的变量
  2. 有序去重:如果需要保留变量在模板中出现的顺序,JS可改用手动过滤方式替代Set:
    const uniqueVariables = variables.filter((item, index) => variables.indexOf(item) === index);
    

内容的提问来源于stack exchange,提问作者James Kehs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 12:23:16