网站项目中十六进制数合法格式校验的正则表达式实现咨询
Solution: Mutually Exclusive Hexadecimal Format Regex
Got it, let's tackle this regex problem step by step. You need to match three distinct, mutually exclusive hexadecimal formats, and your current regex only covers one case—here's how to fix it and enforce the "only one identifier allowed" rule:
First, let's lock in the requirements again to make sure we cover every edge case:
- Legitimate formats (only one can be present per string):
- Prefix:
0xfollowed by one or more hex characters (0-9, A-F, a-f) - Prefix:
$followed by one or more hex characters - Suffix:
h(orHfor case insensitivity) preceded by one or more hex characters
- Prefix:
- No bare hex digits (like
Awithout any prefix/suffix), no overlapping identifiers (like0xa$or$0xA)
Final Regex
^(0x[0-9A-Fa-f]+|\$[0-9A-Fa-f]+|[0-9A-Fa-f]+[hH])$
Breakdown of the Regex
Let's unpack how this enforces your rules:
^and$: These anchor the regex to the start and end of the entire string. This is critical—it ensures we're matching the full input, not just a substring, which blocks invalid cases like0xa$(extra characters at the end) or$0xA(conflicting prefixes).- Three mutually exclusive branches separated by
|:0x[0-9A-Fa-f]+: Matches the0xprefix format. The+fixes your original regex's limitation by requiring at least one hex character after the prefix.\$[0-9A-Fa-f]+: Matches the$prefix format. We escape$with\because it's a special regex character (used to mark the end of a string). The+ensures there's at least one hex digit after the$.[0-9A-Fa-f]+[hH]: Matches thehsuffix format. Here, we require one or more hex characters first, followed by eitherhorH(remove theHif you only want to allow lowercaseh).
- Mutual exclusivity: Each branch is a complete, self-contained format, so there's no way for two identifiers to coexist. For example,
$0xAwon't match any branch—since the second branch expects$to be followed directly by hex digits, not another prefix like0x.
Testing Against Your Examples
Valid Cases (Will Match)
0xA,0xa,0x101,0x747: Matches the first branch101h: Matches the third branch$747: Matches the second branch
Invalid Cases (Will Not Match)
A: No identifier present, doesn't match any branch0xa$: Ends with$, which isn't part of the first branch's structure$0xA:$is followed by0x(not raw hex digits), so it doesn't match the second branch
Optional Adjustments
- If you only want to allow lowercase
hfor the suffix, change[hH]toh - If you need to tolerate leading/trailing whitespace (your examples don't mention this, but it's a common edge case), add
\s*at the start and end:^\s*(0x[0-9A-Fa-f]+|\$[0-9A-Fa-f]+|[0-9A-Fa-f]+[hH])\s*$
内容的提问来源于stack exchange,提问作者flying_loaf_3
相关产品推荐
相关产品推荐

