求匹配9位数字/字母、以/分三组且每组最多4位的正则表达式
Solution for 9-Character Alphanumeric Split into 3 Groups (Max 4 per Group)
Got it, let's nail this regex for you. Your requirement is straightforward: a total of 9 digits and/or letters split into three groups separated by /, with each group containing 1 to 4 characters. No more, no less.
The Working Regex
Here's the regex that checks all your boxes:
^(?=(?:[^A-Za-z0-9]*[A-Za-z0-9]){9}[^A-Za-z0-9]*$)(?:[A-Za-z0-9]{1,4}\/){2}[A-Za-z0-9]{1,4}$
Let's Break It Down
I’ll explain each part so you understand why it works:
^and$: These anchors make sure we match the entire string—no extra characters before or after the pattern.(?=(?:[^A-Za-z0-9]*[A-Za-z0-9]){9}[^A-Za-z0-9]*$): This positive lookahead counts exactly 9 alphanumeric characters, ignoring the/separators. It ensures we don’t have too many or too few total characters.(?:[A-Za-z0-9]{1,4}\/){2}: This matches the first two groups. Each group is 1-4 alphanumeric characters followed by a/. The(?:...)is a non-capturing group (we don’t need to store each group separately unless you want to), and{2}repeats this pattern twice for the first two groups.[A-Za-z0-9]{1,4}: This matches the third and final group, which also has 1-4 alphanumeric characters.
Valid Examples
These will all match the regex:
XX/XXXX/XXX(2 + 4 + 3 = 9 total characters)4444/4444/4(4 + 4 + 1 = 9)ABC/DEFG/HIJ(3 + 4 + 2 = 9)Z/YYYY/XXXX(1 + 4 +4 =9)
Quick Adjustments
- Case Insensitivity: If you want to allow both uppercase and lowercase letters (e.g.,
aBc/DeFg/HiJ), add theiflag (how you do this depends on your programming language or regex tool). - Allow Underscores: If you ever need to include underscores (though you specified digits/letters only), replace
[A-Za-z0-9]with\w(note that\wincludes underscores).
内容的提问来源于stack exchange,提问作者abc def
相关产品推荐
相关产品推荐

