To match 6 digit hexadecimal numbers with JavaScript regular expressions, we can use the /[0-9A-Fa-f]{6}/g regex.
If you are looking for an specific hex character in the middle of the string, you can use "\xhh" where hh is the character in hexadecimal.
'?' is also a quantifier. Is short for {0,1}. It means "Match zero or one of the group preceding this question mark." It can also be interpreted as the part preceding the question mark is optional. e.g.: pattern = re.compile(r'(\d{2}-)?\
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
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
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:]]+/
It's worth mentioning that detecting an MD5 (which is one of the examples) can be done with:
[0-9a-fA-F]{32}
This will match with or without 0x
prefix
(?:0[xX])?[0-9a-fA-F]+
If you're using Perl or PHP, you can replace
[0-9a-fA-F]
with:
[[:xdigit:]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With