Regular expression for a hexadecimal number?

后端 未结 11 1631
旧巷少年郎
旧巷少年郎 2020-11-29 02:56

How do I create a regular expression that detects hexadecimal numbers in a text?

For example, ‘0x0f4’, ‘0acdadecf822eeff32aca5830e438cb54aa722e3’, and ‘8BADF00D’.

11条回答
  •  借酒劲吻你
    2020-11-29 03:50

    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
    

提交回复
热议问题