I am trying to make a minecraft color code parser. I take the original text from a textbox and display the resulting text in the rich textbox. The original text would look something like this:
&4Red
Here, &4
means the text after that should be red color.
abc&4Red&fWhite
This text should look like abc in default color (black), "Red" in red, "White" in white.
So how can I parse the text to separate the text to "abc", "&4Red" and "&fWhite" ?
You will have to learn about
but this does the trick :
var txt = "abc&4Red&fWhite";
// Add color code Black for first item if no color code is specified
if (!txt.StartsWith("&"))
txt = "&0" + txt;
// Create a substrings list by splitting the text with a regex separator and
// keep the separators in the list (e.g. ["&0", "abc", "&4", "Red", "&f", "White"])
string pattern = "(&.)";
var substrings = Regex.Split(txt, pattern).Where(i => !string.IsNullOrEmpty(i)).ToList();
// Create 2 lists, one for texts and one for color codes
var colorCodes = substrings.Where(i => i.StartsWith("&")).ToList();
var textParts = substrings.Where(i => !i.StartsWith("&")).ToList();
// Combine the 2 intermediary list into one final result
var result = textParts.Select((item, index) => new { Text = item, ColorCode = colorCodes[index] }).ToList();