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

如何用正则表达式验证4-5位、前3位为字母的输入格式?

Hey there! Let's walk through these regex requirements clearly—since you mentioned you're new to regular expressions, I'll break down each part so it makes total sense.

1. Validate 4 or 5-character input with first 3 characters as letters

Here's the regex that fits this rule:

^[A-Za-z]{3}[A-Za-z0-9]{1,2}$

Let's break down what each piece does:

  • ^: Anchors the match to the start of the input string (so we don't accidentally match partial strings)
  • [A-Za-z]{3}: Matches exactly 3 uppercase or lowercase letters—this enforces the first 3 characters requirement
  • [A-Za-z0-9]{1,2}: Matches 1 to 2 alphanumeric characters (letters or numbers) to hit the total length of 4 or 5
  • $: Anchors the match to the end of the input string (ensures there are no extra characters after the 4th/5th position)

Note: If you need the last 1-2 characters to be something specific (like only letters or only symbols), just replace [A-Za-z0-9] with your allowed character set.

2. Validate 4-5 character input (4th digit for 4-length, last 2 digits for 5-length) + Your Question

First, answering your question: Based on your examples (WER4, ASD23), yes—this rule does require the first 3 characters to be letters (since both examples follow that pattern). Here's the regex that handles this perfectly:

^[A-Za-z]{3}\d{1,2}$

Let's break this down simply:

  • ^[A-Za-z]{3}: Same as above—locks in the first 3 characters as letters
  • \d{1,2}: Matches 1 or 2 digits (\d is shorthand for [0-9], so this covers both your 4-digit and 5-digit cases)
  • $: Makes sure there are no extra characters tacked on at the end

This regex will correctly match your examples:

  • WER4: 3 letters + 1 digit (total length 4) → matches
  • ASD23: 3 letters + 2 digits (total length 5) → matches

If for some reason you didn't need the first 3 characters to be letters, we could tweak the regex, but your examples make it clear that's part of the requirement.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:37:16