Extract Hex Digits From a String
By 
Steve on 
Tuesday, January 09, 2007
Updated 
Friday, April 22, 2016
Viewed 
24,527 times. (
9 times today.)
 
 
 
Summary
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)
      lblOutput.Text 
         += h + " -> " + Snippets00003.ExtractHexDigits(h) + "<br>";
} 
If you run the previous method you'll get the following output:
 
Example: Output
#FFFFFF -> FFFFFF
xAE -> AE
'7AEAEAEAE'H -> 7AEAEAEAE
 
namespace Cambia.CoreLib
{
   using System;
   using System.Text.RegularExpressions;
   /// <summary>
   /// Useful C# snippets from CambiaResearch.com
   /// </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;
      }
   }
}