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

正则表达式匹配咨询:需匹配--word/--no-word,排除---word类多短横线前缀

Solution for Matching --word/--no-word but not ---word

Got it, let's fix that regex for you. The original pattern ^--([\w|-]+) has a couple of issues: first, it allows extra hyphens at the start (like ---word gets matched because the third hyphen falls into the [\w|-]+ group), and second, the | inside the character class is unnecessary—it's treated as a literal pipe character instead of an OR operator (character classes already handle OR implicitly).

The Fixed Regex

^--(?!-)([\w-]+)

Breakdown of Changes

Let's break down why this works:

  • ^ : Anchors the match to the start of the string (so we don't match hyphens in the middle of text)
  • -- : Explicitly matches exactly two leading hyphens
  • (?!-) : A negative lookahead that ensures the next character after the two hyphens is NOT another hyphen. This is the key part that blocks ---word or ----word from being matched.
  • ([\w-]+) : Matches one or more word characters (letters, numbers, underscores) OR hyphens—perfect for capturing values like word or no-word. We removed the redundant | here since character classes already include all listed characters as options.

Test Cases

Let's verify this works as expected:

  • ✅ Matches: --word, --no-word, --my-custom-word
  • ❌ Doesn't match: ---word, ----word, -word, word, -- (empty after hyphens)

If you need to match the entire string (not just the start), add a $ at the end to anchor it:

^--(?!-)([\w-]+)$

That should cover exactly what you're looking for!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:33:37