| Snippet | Conversions | Regular Expressions | Text and Strings | C# | .NET |
SummaryThis 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
public void TestExtractHexDigits()
{
string[] hex = new string[3];
hex[0] = "#FFFFFF";
hex[1] = "xAE";
hex[2] = "'7AEAEAEAE'H";
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>
///
/// </summary>
public class Snippets00003
{
public Snippets00003()
{
}
/// <summary>
///
/// </summary>
public static string ExtractHexDigits(string input)
{
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;
}
}
} |
|