Check if string is a valid representation of a HEX number

I am a complete noob regarding regex

. My goal is to check that the string is a valid representation of the HEX number. Currently my implementation (which I find very inefficient) has a list with all HEX numbers (0,1, ... 9, A, B..F) and checks that my string contains characters not contained in the given list. I bet it can be done easily with regex, but I have no idea on how to implement it.

 private bool ISValidHEX(string s)
           List<string> ToCheck = new List<string>();
           for (int i = 0; i < 10; i++)
           for (int i = 0; i < s.Length; i++)
               if( !ToCheck.Contains(s.Substring(i,1)))
                   return false;
           return true;



source to share

5 answers

I would think the fastest way is to try to convert your string to an integral type and handle any exception. Use the following code:

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


The resulting code is arguably easier to track than a regex, and is especially useful if you need a parsed value (otherwise you could use Int32.TryParse

, which is properly documented in other answers).

(One of my favorite quotes is Jamie Zawinski: "Some people, when faced with a problem, think," I know, I will use regular expressions. "Now they have two problems."



To just check

Check if string is a valid representation of a HEX number

you can use a method like:

int res = 0; 
         System.Globalization.CultureInfo.InvariantCulture, out res)) {

      //IT A VALID HEX


Pay attention to the parameter System.Globalization.CultureInfo.InvariantCulture

, change it according to your needs.



I recommend using Int32.TryParse . There is an overload that allows converting numbers to hexadecimal numbers

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 case you have an invalid hex or an Int32.MaxValue overflows, you won't get an exception, but you can just check the boolean return value.

Warning: string cannot be prefixed "0x" or "& H"




will match strings that are numbers and valid hex letters, but that doesn't match the possible 0x in front. I'm sure you can add that if needed.



I've tried google search. I have found many solutions. Here are two:

Check Hex color code with regex

Regular expression to test for a hexadecimal number


//use System.Text.RegularExpressions before using this function
public bool vldRegex(string strInput)
//create Regular Expression Match pattern object
Regex myRegex = new Regex("^[a-fA-F0-9]+$");
//boolean variable to hold the status
bool isValid = false;
if (string.IsNullOrEmpty(strInput))
   isValid = false;
   isValid = myRegex.IsMatch(strInput);
//return the results
return isValid;




All Articles