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

JS正则表达式定制需求:允许字母数字短横线,禁止单独短横线

Solution to Exclude Hyphen-Only Strings from Your Regex

Absolutely! You can easily tweak your regex to block strings made up entirely of hyphens, while still keeping valid combinations of letters, numbers, and hyphens. Here's the revised pattern:

^(?!-+$)[a-z0-9-]+$

Let’s break down what each part does:

  • ^ and $: Anchor the match to the start and end of the string, ensuring we check the entire input (not just a substring).
  • (?!-+$): This is a negative lookahead assertion. It checks if the entire string from start to end is nothing but hyphens. If that’s the case, the match fails immediately. If there’s at least one letter or number mixed in, it proceeds.
  • [a-z0-9-]+: Your original character set, which matches one or more lowercase letters, numbers, or hyphens.

Test Cases

  • Valid matches (will pass): 3e-qw, -3-, -a- — these all contain at least one alphanumeric character alongside hyphens.
  • Invalid matches (will fail): ---, - — these are made up solely of hyphens, so the negative lookahead blocks them.

Optional Adjustment

If you need to allow uppercase letters too, you can either expand the character set to [a-zA-Z0-9-]+ or add a case-insensitive modifier (like /^(?!-+$)[a-z0-9-]+$/i if using regex in a programming language that supports modifiers).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:03:57