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

JavaScript正则表达式需求:匹配指定模板变量,排除无参数变量

Solution for Targeted Regex Matching in JavaScript

Got it, let's work through this regex problem together. You need to match the {{report date, [[YYYY]]}} and {{report date, [[MM]]}} placeholders while excluding {{global_now_date}}—and you already have a solid start on the trailing part of the regex. Let's tie it all up properly.

The Final Regex

Here's the complete regex that meets your requirements:

/{{report date, \[\[(YYYY|MM)\]\]}}/g

Breakdown of How It Works

Let's break this down piece by piece to make sure you understand why it works:

  • {{report : This starts the match by targeting only placeholders that begin with {{report —this immediately excludes {{global_now_date}} since its opening is {{global_, which doesn't match.
  • date, \[\[: Matches the literal date, [[ (we escape the square brackets with \ because they're special characters in regex).
  • (YYYY|MM): This is a capture group that matches either YYYY or MM—use this if you want to specifically target those two date components. If you ever need to match any content inside the double brackets (not just YYYY/MM), you can replace this with .*? (the non-greedy wildcard you were using earlier).
  • \]\]}}: Matches the closing ]]}} (again, escaping the square brackets).
  • The g flag at the end makes the regex search for all matches in the string, not just the first one.

Example Usage in JavaScript

Here's how you'd use this regex with your sample string:

const inputStr = "{{global_now_date}}-{{report date, [[YYYY]]}}-{{report date, [[MM]]}}-{{job_id}}_test_1_{{bca clause}}-Rev-{{report revision no.}}";
const targetRegex = /{{report date, \[\[(YYYY|MM)\]\]}}/g;
const matchedPlaceholders = inputStr.match(targetRegex);

console.log(matchedPlaceholders);
// Output: ["{{report date, [[YYYY]]}}", "{{report date, [[MM]]}}"]

Why This Doesn't Match {{global_now_date}}

Since the regex explicitly starts with {{report , there's no way it can match {{global_now_date}}—the opening characters don't align at all. That's a clean, straightforward way to exclude the unwanted placeholder without needing complex negative lookaheads (though those are an option if your use case ever gets more complicated).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:44:02