Check if string is valid represantion of HEX number

I would have thought that it's quickest to attempt to convert your string to an integral type and deal with any exception. Use code like this:

int num = Int32.Parse(s, System.Globalization.NumberStyles.HexNumber);

The resulting code is possibly easier to follow than a regular expression and is particularly useful if you need the parsed value (else you could use Int32.TryParse which is adequately documented in other answers).

(One of my favourite quotations is by Jamie Zawinski: "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems.")


To simply check

Check if string is valid represantion of HEX number

you may use a method like:

int res = 0; 
if(int.TryParse(val, 
         System.Globalization.NumberStyles.HexNumber, 
         System.Globalization.CultureInfo.InvariantCulture, out res)) {

      //IT'S A VALID HEX
}

Pay attention on System.Globalization.CultureInfo.InvariantCulture parameter, change it according to your needs.


I recommend to use Int32.TryParse. There is an overload that allow the Hex numbers conversion

int v;
string test = "FF";
if(Int32.TryParse(test, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out v))
   Console.WriteLine("Is HEX:" + v.ToString());

This is better than a simple Int32.Parse because, in the case that you have an invalid hex or the conversion overflows the Int32.MaxValue you don't get an exception but you could simply test the boolean return value.

Warning, the string cannot be prefixed with "0x" or "&H"

Tags:

C#

Hex

Regex