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

输入文本框Regex校验需求:支持字母数字且首尾不可含连字符

Regex for Alphanumeric Input with Allowed Middle Hyphens

Got it, let's break down how to build the perfect regex for your input validation needs. Here's the regex you can use directly:

^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$

Let's unpack each part to understand exactly how it enforces your rules:

  • ^: Anchors the match to the start of the string — this ensures we never have a leading hyphen.
  • [A-Za-z0-9]+: Matches one or more alphanumeric characters right at the start, so the first character is always valid (no hyphen allowed here).
  • (?:-[A-Za-z0-9]+)*: This non-capturing group handles valid middle hyphens:
    • -: Matches a single hyphen
    • [A-Za-z0-9]+: Ensures the hyphen is immediately followed by one or more alphanumeric characters (prevents consecutive hyphens or hyphens at the end)
    • *: Lets this group repeat zero or more times — meaning the string can have no hyphens at all, or multiple valid hyphen-separated segments.
  • $: Anchors the match to the end of the string — stops any trailing hyphens from slipping through.

Valid Test Cases:

  • abc123 (pure alphanumeric, no hyphens)
  • user-123-profile (multiple valid middle hyphens)
  • XYZ-789 (mix of uppercase letters and numbers with a single hyphen)

Invalid Test Cases (that the regex will reject):

  • -startWithHyphen (leading hyphen)
  • endWithHyphen- (trailing hyphen)
  • double--hyphens (consecutive hyphens)
  • invalid!char (contains non-alphanumeric symbols)

Quick Implementation Examples:

In JavaScript, you can validate a user input string like this:

const validationRegex = /^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$/;
const userInput = document.getElementById('yourInput').value;
const isInputValid = validationRegex.test(userInput);

Or directly in HTML, attach it to an input's pattern attribute for built-in browser validation:

<input 
  type="text" 
  pattern="^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$" 
  title="Only alphanumeric characters allowed; hyphens are permitted only in the middle (no leading/trailing hyphens)"
>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:41:47