如何为特定格式的不定长字母数字字符串生成正则表达式?
Hey there! Let's put together the right regex for your exact use case. Here's a breakdown of what works, plus some variations to cover edge cases:
Basic Regex (Matches Your Example Format)
This will match strings that follow the XX-XX-XX... pattern, with no trailing hyphen, and any number of two-character segments (at least one segment, or more if needed):
^[A-Za-z0-9]{2}(-[A-Za-z0-9]{2})+$
What Each Part Does:
^: Anchors the match to the start of the string (so we don't accidentally match partial strings)[A-Za-z0-9]{2}: Matches exactly 2 alphanumeric characters (uppercase/lowercase letters, digits)(-[A-Za-z0-9]{2})+: Matches one or more instances of a hyphen followed by 2 alphanumeric characters$: Anchors the match to the end of the string (prevents extra invalid characters at the end)
Allow Single Two-Character Segment (No Hyphens)
If you want to also match a standalone pair like AB or 12 (along with longer hyphen-separated strings), switch the + to * (which means "zero or more"):
^[A-Za-z0-9]{2}(-[A-Za-z0-9]{2})*$
For Hexadecimal-Specific Strings (Like Your Example)
Since your sample uses hex characters (0-9, A-F, a-f), you can narrow down the character class to only match valid hex digits:
^[0-9A-Fa-f]{2}(-[0-9A-Fa-f]{2})*$
If your regex engine supports case-insensitive matching, you can simplify it with the /i modifier:
^[0-9A-F]{2}(-[0-9A-F]{2})*$/i
Quick Test Cases
- Matches:
00-13-50-FF-FE-11-D8-3A(your example),AB-CD,12,FF-00-AA - Doesn't Match:
A-BC(single character before hyphen),AB-CD-(trailing hyphen),AB_12(non-alphanumeric character)
内容的提问来源于stack exchange,提问作者vinayak temgire

