It's hard enough to find an error in your code when you're looking for it; it's even harder when you've assumed your code is error-free. --Steve McConnell
Welcome to my blog and project site for Microsoft.NET development.

I've been a full time .NET developer for ten years, but I didn't start my professional life as a programmer ... more
Share/Print this page:

Extract Hex Digits From a String

By steve on January 09, 2007.
Updated on January 22, 2012.
Viewed 9,968 times (0 times today).
Article TypesLanguage ElementsLanguage ElementsLanguage ElementsLanguagesTechnologies
SnippetConversionsRegular ExpressionsText and StringsC#.NET

Summary

Contents

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

Contents
// 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

Contents
#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;
      }


   }
}
Back to Top

User Comments (0)

Post Your Comment
  You may post without logging in or login here.
Display Name: Required.
Email: Required. Will not be shown. Used for identicon.
Comment:
Allowed tags: <quote></quote>, <code></code>, <b></b>, <i></i>, <u></u>, <red></red>
 
   Please type text as shown in the image at left.