Regular expression for a hexadecimal number?
Solution 1:
How about the following?
0[xX][0-9a-fA-F]+
Matches expression starting with a 0, following by either a lower or uppercase x, followed by one or more characters in the ranges 0-9, or a-f, or A-F
Solution 2:
The exact syntax depends on your exact requirements and programming language, but basically:
/[0-9a-fA-F]+/
or more simply, i
makes it case-insensitive.
/[0-9a-f]+/i
If you are lucky enough to be using Ruby, you can do:
/\h+/
EDIT - Steven Schroeder's answer made me realise my understanding of the 0x bit was wrong, so I've updated my suggestions accordingly. If you also want to match 0x, the equivalents are
/0[xX][0-9a-fA-F]+/
/0x[0-9a-f]+/i
/0x[\h]+/i
ADDED MORE - If 0x needs to be optional (as the question implies):
/(0x)?[0-9a-f]+/i
Solution 3:
Not a big deal, but most regex engines support the POSIX character classes, and there's [:xdigit:]
for matching hex characters, which is simpler than the common 0-9a-fA-F
stuff.
So, the regex as requested (ie. with optional 0x
) is: /(0x)?[[:xdigit:]]+/
Solution 4:
It's worth mentioning that detecting an MD5 (which is one of the examples) can be done with:
[0-9a-fA-F]{32}
Solution 5:
This will match with or without 0x
prefix
(?:0[xX])?[0-9a-fA-F]+