The best is the enemy of the good. --Voltaire

Extract Hex Digits From a String


This is a simple little routine that uses the .NET Regex class to extract only the hex digits from an input string (0-9, A-F). Since hex digits or colors in string form may often be preceded by other characters such as 'x' or '#' this method allows you to easily standardize the format of the hex string.

Extracting Hex Digits

// Add this method to an ASP.NET page with a Label control lblOutput.

public void TestExtractHexDigits()
   // invent a few hex string with extra characters
   string[] hex = new string[3];
   hex[0] = "#FFFFFF";
   hex[1] = "xAE";
   hex[2] = "'7AEAEAEAE'H";

   // extract the hex digits and write to web page
   lblOutput.Text = "";
   foreach (string h in hex)
         += h + " -> " + Snippets00003.ExtractHexDigits(h) + "<br>";


If you run the previous method you'll get the following output:

Example: Output

xAE -> AE
namespace Cambia.CoreLib
   using System;
   using System.Text.RegularExpressions;

   /// <summary>
   /// Useful C# snippets from
   /// </summary>
   public class Snippets00003

      public Snippets00003()

      /// <summary>
      /// Extract only the hex digits from a string.
      /// </summary>
      public static string ExtractHexDigits(string input)
         // remove any characters that are not digits (like #)
         Regex isHexDigit 
            = new Regex("[abcdefABCDEF\\d]+", RegexOptions.Compiled);
         string newnum = "";
         foreach (char c in input)
            if (isHexDigit.IsMatch(c.ToString()))
               newnum += c.ToString();
         return newnum;