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

能否构造符合三部分规则且总长不超过28字符的正则表达式?

Yes, this is totally doable with a regular expression!

Here's a clean, readable regex that satisfies all your requirements, plus a breakdown of each part:

^(?=.{5,28}$)[0-9a-zA-Z]+ - [0-9a-zA-Z]+$

Let's break it down step by step:

  • ^ and $: These are start/end anchors—they make sure the regex matches the entire string, not just a piece of it.
  • (?=.{5,28}$): This is a positive lookahead that checks the total length of the string is between 5 and 28 characters. The minimum 5 comes from 1 (first substring) + 3 (the fixed " - ") + 1 (third substring), and 28 is your specified max total length.
  • [0-9a-zA-Z]+: Matches the first substring—one or more alphanumeric characters (digits 0-9, lowercase a-z, uppercase A-Z). The + guarantees it's at least 1 character long, with no upper limit beyond what the total length constraint allows.
  • -: Explicitly matches the fixed second substring—make sure to include the spaces around the hyphen exactly as specified!
  • The final [0-9a-zA-Z]+: Matches the third substring, following the same rules as the first one.

Why this works:

  • It ensures neither the first nor third substring can be empty (thanks to the + quantifier).
  • The lookahead keeps the total string length within your 28-character limit, no matter how you split the remaining characters between the first and third parts.
  • It strictly enforces the alphanumeric rule for the variable parts and the exact separator in between.

This regex works in most modern regex engines (like JavaScript, Python's re module, PCRE, etc.). If you're using an older engine that doesn't support lookaheads, we can adjust to a more verbose version, but the lookahead approach is by far the most maintainable.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:48:08