求匹配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 betweencopyand 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
相关产品推荐
相关产品推荐

