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

求助:如何为含两个连字符的12位字母数字串添加Regex长度校验

Fixing Your Regex for 12-Character Alphanumeric Strings with Exact Two Hyphens

Got it, let's get this sorted for you. The core issue with your original regex is that it correctly enforces exactly two hyphens but doesn't restrict the total length to 12 characters. Here's the corrected regex that meets all your requirements:

^(?=.{12}$)([a-zA-Z0-9]*-[a-zA-Z0-9]*){2}$

Let's break down what each part does:

  • ^ and $: Anchor the regex to match the entire string (so partial matches don't slip through).
  • (?=.{12}$): A positive lookahead that ensures the total length of the string is exactly 12 characters.
  • ([a-zA-Z0-9]*-[a-zA-Z0-9]*){2}: This repeats your original group twice, which guarantees exactly two hyphens. Each group matches:
    • [a-zA-Z0-9]*: Zero or more alphanumeric characters (allows hyphens at the start or end of the string, like your example -abcd-abcdacb—though that one is too long, the regex will reject it thanks to the length check).
    • -: A single hyphen.

Bonus: Explicitly exclude spaces (though your original regex already does this)

Since [a-zA-Z0-9] doesn't include spaces, any string with spaces will automatically fail to match. If you want to make this even clearer, you could add another lookahead to ensure no spaces are present:

^(?=.{12}$)(?![^ ]* )([a-zA-Z0-9]*-[a-zA-Z0-9]*){2}$

But this is optional—your original character class already blocks spaces.

Testing against your examples:

  • Valid matches (when adjusted to 12 characters):
    • abcd12-avc-a (length 12: 6 + 1 + 3 + 1 + 1 = 12)
    • 1234-abcd-56 (4 + 1 +4 +1 +2 =12)
  • Rejected cases:
    • 1234abcd-ab (length 10, fails the 12-character check)
    • -abcd-abcdacb (length 14, too long)
    • ac12-acdsde- (length 10, too short)
    • -abcd-abcd--a (three hyphens, fails the exact two-hyphen rule)
    • abcd-abcdefg (one hyphen, fails the two-hyphen rule)

The key addition here is the (?=.{12}$) lookahead, which locks in the total length while keeping your original logic for hyphen count intact.

内容的提问来源于stack exchange,提问作者capt.swag

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:45:27