Cambia Research - Supporting the Microsoft .NET Developer Community Supporting the Microsoft .NET Developer Community  

     | Home  | Articles  | Categories  | Coders  | Search  | Submit  | Contact Us    
Computers are good at following instructions, but not at reading your mind. --Donald Knuth

Share Your Knowledge! -- Create and submit your articles the easy way with WebWriter.

Updated:10:24 AM CT Feb 02, 2007
Posted:11:03 PM CT Jan 09, 2007

Extract Hex Digits From a String

Author: Steve Lautenschlager

SnippetConversionsRegular ExpressionsText and StringsC#.NET

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


   }
}

Add New Comment
CR Comments by Cambia Research
advertisement
 
Steve Lautenschlager (steve)
Steve is the founder and creator of Cambia Research. Developing and maintaining the site combines his passions for technology, writing and education.
Steve holds a Ph.D. in particle physics from Duke University, has worked at CERN, the European center for particle physics (where the web was born) and in Microsoft's web division with microsoft.com, msnbc.com and other web properties. Steve is a web consultant specializing in Microsoft.NET technologies. Read more here.


 
Copyright © Cambia Research 2002-2007. All Rights Reserved. steve [ at ] cambiaresearch.com