Regular expression for hexadecimal number?

How to create a regular expression that defines hexadecimal numbers in the text?

For example, '0x0f4,' 0acdadecf822eeff32aca5830e438cb54aa722e3 and '8BADF00D.

+65
regex
Feb 10 2018-12-12T00:
source share
9 answers

What about the following?

0[xX][0-9a-fA-F]+ 

Matches an expression starting with 0, following either lower or upper case x, followed by one or more characters in the ranges 0-9 or af or AF

+111
Feb 10 '12 at 1:10
source share
β€” -

The exact syntax depends on your exact requirements and programming language, but basically:

 /[0-9a-fA-F]+/ 

or more simply, i makes the case insensitive.

 /[0-9a-f]+/i 

If you are fortunate enough to use Ruby, you can do:

 /\h+/ 

EDIT - Steven Schroeder's answer made me realize that my understanding of 0x bits was wrong, so I updated my suggestions accordingly. If you also want to combine 0x, equivalents

 /0[xX][0-9a-fA-F]+/ /0x[0-9a-f]+/i /0x[\h]+/i 

ADD MORE . If 0x should be optional (as follows from the question):

 /(0x)?[0-9a-f]+/i 
+28
Feb 10 '12 at 1:11
source share

It doesn't matter, but most regex engines support POSIX character classes, and there [:xdigit:] for matching hexadecimal characters, which is simpler than regular 0-9a-fA-F material.

So, the regular expression as requested (i.e. with optional 0x ): /(0x)?[[:xdigit:]]+/

+13
Feb 26 '14 at 21:13
source share

This will match the 0x prefix or without it

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

+10
Jul 01 '13 at 13:35
source share

It should be noted that MD5 detection (which is one example) can be performed using

 [0-9a-fA-F]{32} 
+7
Sep 08 '14 at 1:00 p.m.
source share

If you use Perl or PHP, you can replace

 [0-9a-fA-F] 

from:

 [[:xdigit:]] 
+3
Aug 12 '15 at 14:41
source share

For the record only, I would indicate the following:

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

Which is different in that it checks that it has to contain six valid characters, and in lower and upper case x if we have one.

+3
Jul 06 '16 at 21:16
source share

If you are looking for a specific hexadecimal character in the middle of a string, you can use "\ xhh", where hh is a character in hexadecimal format. I tried and it works. I use the framework for C ++ Qt, but it can solve problems in other cases, depending on the taste you need to use (php, javascript, python, golang, etc.).

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

0
Jan 02 '17 at 15:29
source share

This ensures that you have no more than three valid pairs:

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

It is not possible to match any or more than three pairs of valid characters.

-one
Sep 18 '14 at 17:53
source share



All Articles