Regular expression for a hexadecimal number?

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

Tags:

Regex