You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
27 lines
718 B
TypeScript
27 lines
718 B
TypeScript
// 提示词模板变量解析工具
|
|
// 支持形如 ${variable_name} 或 ${{ variable_name }} 的占位符
|
|
|
|
/**
|
|
* 从提示词模板中提取所有变量名。
|
|
* 匹配规则:
|
|
* - ${xxx}
|
|
* - ${{ xxx }}
|
|
* 返回变量名数组(去重,按出现顺序)
|
|
*/
|
|
export function extractPromptVariables(prompt: string): string[] {
|
|
if (!prompt) return [];
|
|
const vars: string[] = [];
|
|
const set = new Set<string>();
|
|
// 同时匹配 ${var} 和 ${{ var }}
|
|
const re = /\$\{\s*([^{}]+?)\s*\}/g;
|
|
let m: RegExpExecArray | null;
|
|
while ((m = re.exec(prompt)) !== null) {
|
|
const name = m[1]?.trim();
|
|
if (name && !set.has(name)) {
|
|
set.add(name);
|
|
vars.push(name);
|
|
}
|
|
}
|
|
return vars;
|
|
}
|