I wrote this Console.Write function to use in my applications where I need to easily color-code output.
Example syntax would be:
Console.WriteLine("<f=red>this is in red");
Console.WriteLine("<b=gray><f=white>This is white on gray. <f=green>This is green on gray. <b=darkmagenta>This is green on dark magenta. <b=d>This is green on default.");
Which results in this...

I'm looking for a general review of the code.
//github.com/BenVlodgi/CommandHelper
public static class Console
{
private static Regex _writeRegex = new Regex("<[fb]=\\w+>");
public static void WriteLine(string value, int? cursorPosition = null, bool clearRestOfLine = false)
{
Write(value + Environment.NewLine, cursorPosition, clearRestOfLine);
}
public static void Write(string value, int? cursorPosition = null, bool clearRestOfLine = false)
{
if (cursorPosition.HasValue)
System.Console.CursorLeft = cursorPosition.Value;
ConsoleColor defaultForegroundColor = System.Console.ForegroundColor;
ConsoleColor defaultBackgroundColor = System.Console.BackgroundColor;
var segments = _writeRegex.Split(value);
var colors = _writeRegex.Matches(value);
for (int i = 0; i < segments.Length; i++)
{
if (i > 0)
{
ConsoleColor consoleColor;
// Now that we have the color tag, split it int two parts,
// the target(foreground/background) and the color.
var splits = colors[i - 1].Value
.Trim(new char[] { '<', '>' })
.Split('=')
.Select(str => str.ToLower().Trim())
.ToArray();
// if the color is set to d (default), then depending on our target,
// set the color to be the default for that target.
if (splits[1] == "d")
if (splits[0][0] == 'b')
consoleColor = defaultBackgroundColor;
else
consoleColor = defaultForegroundColor;
else
// Grab the console color that matches the name passed.
// If none match, then return default (black).
consoleColor = Enum.GetValues(typeof(ConsoleColor))
.Cast<ConsoleColor>()
.FirstOrDefault(en => en.ToString().ToLower() == splits[1]);
// Set the now chosen color to the specified target.
if (splits[0][0] == 'b')
System.Console.BackgroundColor = consoleColor;
else
System.Console.ForegroundColor = consoleColor;
}
// Only bother writing out, if we have something to write.
if (segments[i].Length > 0)
System.Console.Write(segments[i]);
}
System.Console.ForegroundColor = defaultForegroundColor;
System.Console.BackgroundColor = defaultBackgroundColor;
if (clearRestOfLine)
ClearRestOfLine();
}
public static void ClearRestOfLine()
{
int winTop = System.Console.WindowTop;
int left = System.Console.CursorLeft;
System.Console.Write(new string(' ', System.Console.WindowWidth - left));
System.Console.CursorLeft = left;
System.Console.CursorTop--;
System.Console.WindowTop = winTop;
}
}