Regular expression for a hexadecimal number?

后端 未结 11 1590
旧巷少年郎
旧巷少年郎 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
    
    0 讨论(0)
  • 2020-11-29 03:51

    Just for the record I would specify the following:

    /^[xX]?[0-9a-fA-F]{6}$/
    

    Which differs in that it checks that it has to contain the six valid characters and on lowercase or uppercase x in case we have one.

    0 讨论(0)
  • 2020-11-29 03:53

    This will match with or without 0x prefix

    (?:0[xX])?[0-9a-fA-F]+

    0 讨论(0)
  • 2020-11-29 03:55

    It's worth mentioning that detecting an MD5 (which is one of the examples) can be done with:

    [0-9a-fA-F]{32}
    
    0 讨论(0)
  • 2020-11-29 03:56

    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

    0 讨论(0)
提交回复
热议问题