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

求匹配Handlebar表达式及默认值的正则表达式

Fixing Regex for Handlebars-Style {{copy}} Expressions

Got it, let's sort out this regex issue for your {{copy}} patterns. Your initial attempt \b{{copy*}}\b doesn't work because:

  • \b (word boundary) doesn't play nice with {{/}} (these aren't "word characters")
  • copy* matches "cop" followed by any number of "y"s, which isn't what you want
  • It doesn't account for the optional default value parameter

Correct Regex Pattern

Here's a regex that matches all your target scenarios—including expressions with or without single-quoted default values:

{{copy(?:\s+'([^']+)')?}}

Let's break down what each part does:

  • {{copy: Matches the literal start of your expression
  • (?:\s+'([^']+)')?: An optional non-capturing group for the default value:
    • \s+: Matches one or more spaces between copy and the quote
    • '([^']+)': Captures the content inside single quotes (matches any character except ')
    • ?: Makes the entire default value section optional (so it works for plain {{copy}} too)

If You Need to Support Double Quotes

If your default values might use double quotes instead (or both), adjust the regex to:

{{copy(?:\s+["']([^"']+))?}}

Example Usage (JavaScript)

Here's how you'd extract all matches and their default values:

const inputStr = "{{copy}} some text, then {{copy}}, then some other other text some {{copy 'default value here'}} here";
const regex = /{{copy(?:\s+'([^']+)')?}}/g;

// Extract all matches
const matches = [...inputStr.matchAll(regex)];

matches.forEach((match, index) => {
  console.log(`Match ${index + 1}: ${match[0]}`);
  if (match[1]) {
    console.log(`  Default value: "${match[1]}"`);
  }
});

Output:

Match 1: {{copy}}
Match 2: {{copy}}
Match 3: {{copy 'default value here'}}
  Default value: "default value here"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:11:33