Regular expression for a hexadecimal number?

后端 未结 11 1589
旧巷少年郎
旧巷少年郎 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:33

    This one makes sure you have no more than three valid pairs:

    (([a-fA-F]|[0-9]){2}){3}
    

    Any more or less than three pairs of valid characters fail to match.

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

    Another example: Hexadecimal values for css colors start with a pound sign, or hash (#), then six characters that can either be a numeral or a letter between A and F, inclusive.

    ^#[0-9a-fA-F]{6}
    
    0 讨论(0)
  • 2020-11-29 03:35

    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:]]+/

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

    If you're using Perl or PHP, you can replace

    [0-9a-fA-F]
    

    with:

    [[:xdigit:]]
    
    0 讨论(0)
  • 2020-11-29 03:38

    In case you need this within an input where the user can type 0 and 0x too but not a hex number without the 0x prefix:

    ^0?[xX]?[0-9a-fA-F]*$
    
    0 讨论(0)
  • 2020-11-29 03:47

    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. I've tried and it works. I use framework for C++ Qt but it can solve problems in other cases, depends on the flavor you need to use (php, javascript, python , golang, etc.).

    This answer was taken from:http://ult-tex.net/info/perl/

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