|
| 1 | +/** |
| 2 | + * Inner regex pattern for prompt variable names (without braces or `?` prefix) |
| 3 | + * |
| 4 | + * Pattern: /[^{}\s](?:[^{}]*[^{}\s])?/ |
| 5 | + * |
| 6 | + * Breakdown: |
| 7 | + * | Part | Meaning | |
| 8 | + * | -------------- | ---------------------------------------------------------- | |
| 9 | + * | `[^\s{}]` | First character: not whitespace, `{`, or `}` | |
| 10 | + * | `(?:...)?` | Optional non-capturing group (allows single-char names) | |
| 11 | + * | `[^{}]*` | Middle characters: any except `{` or `}` (spaces allowed) | |
| 12 | + * | `[^\s{}]` | Last character: not whitespace, `{`, or `}` | |
| 13 | + * |
| 14 | + * This inner pattern is reused in: |
| 15 | + * - PROMPT_VARIABLE_TEXT_PATTERN: Matches "?Name" format (with anchors) |
| 16 | + * - PROMPT_VARIABLE_PATTERN: Matches "{{?Name}}" format (in templates) |
| 17 | + * |
| 18 | + * Valid examples: "Name", "Prompt Var", "x" |
| 19 | + * Invalid examples: " Name", "Name ", "{Name}", "Na{me}" |
| 20 | + */ |
| 21 | +const PROMPT_VARIABLE_PATTERN = /[^{}\s](?:[^{}]*[^{}\s])?/; |
| 22 | + |
| 23 | +/** |
| 24 | + * Valid examples: "?Name", "?Prompt Var", "?x" |
| 25 | + * Invalid examples: "? Name", "?Name ", "?{{Name}}", "?{Name}" |
| 26 | + */ |
| 27 | +export const PROMPT_VARIABLE_TEXT_PATTERN = new RegExp(`^\\?(${PROMPT_VARIABLE_PATTERN.source})$`); |
| 28 | + |
| 29 | +/** |
| 30 | + * Valid matches: "{{?Name}}", "{{?Prompt Var}}", "{{?x}}" |
| 31 | + * Invalid: "{{? Name}}", "{{?Name }}", "{{?{Name}}}" |
| 32 | + */ |
| 33 | +export const PROMPT_VARIABLE_TEMPLATE_PATTERN = new RegExp(`{{\\?(${PROMPT_VARIABLE_PATTERN.source})}}`, 'g'); |
| 34 | + |
1 | 35 | /** |
2 | 36 | * Extract prompt variables matching {{?<Prompt Text>}} from a string. |
3 | 37 | * @param {string} str - The input string. |
4 | 38 | * @returns {string[]} - An array of extracted prompt variables. |
5 | 39 | */ |
6 | 40 | export const extractPromptVariablesFromString = (str: string): string[] => { |
7 | | - const regex = /{{\?([^}]+)}}/g; |
8 | 41 | const prompts = new Set<string>(); |
9 | 42 | let match; |
10 | | - while ((match = regex.exec(str)) !== null) { |
11 | | - prompts.add(match[1].trim()); |
| 43 | + while ((match = PROMPT_VARIABLE_TEMPLATE_PATTERN.exec(str)) !== null) { |
| 44 | + prompts.add(match[1]); |
12 | 45 | } |
13 | 46 | return Array.from(prompts); |
14 | 47 | }; |
|
0 commit comments