正则表达式匹配咨询:需匹配--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---wordor----wordfrom being matched.([\w-]+): Matches one or more word characters (letters, numbers, underscores) OR hyphens—perfect for capturing values likewordorno-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
相关产品推荐
相关产品推荐

