using System.Text.RegularExpressions;
private static string ToggleRichText(string text, string tag, int start, int end, string args = "")
string pretext = text.Substring(0, start);
string selected = text.Substring(start, end - start);
string postext = text.Substring(end);
var regex = new Regex($@"<\/?{tag}([^>]*)>", RegexOptions.RightToLeft);
var pretextmatch = regex.Match(pretext);
var startsTagged = pretextmatch.Success && pretextmatch.Value != $"</{tag}>";
var pretextArgs = startsTagged ? pretextmatch.Groups[1].Captures[0].Value : "";
var selectedmatch = regex.Match(selected);
var containsTags = selectedmatch.Success;
var endsUntagged = containsTags && selectedmatch.Value == $"</{tag}>";
var posttextArgs = containsTags && !endsUntagged ? selectedmatch.Groups[1].Captures[0].Value : pretextArgs;
selected = regex.Replace(selected, "");
if (startsTagged && args != pretextArgs && !endsUntagged){
selected = $"</{tag}><{tag}{args}>" + selected + $"</{tag}><{tag}{posttextArgs}>";
}else if (startsTagged && args != pretextArgs && endsUntagged){
selected = $"</{tag}><{tag}{args}>" + selected + $"</{tag}>";
}else if (startsTagged && endsUntagged){
}else if (!startsTagged && containsTags && !endsUntagged){
selected = $"<{tag}{args}>" + selected;
selected = $"</{tag}>" + selected + $"<{tag}{args}>";
selected = $"<{tag}{args}>" + selected + $"</{tag}>";
return pretext + selected + postext;
public static void Main()
var content = "This is the string that has <b>bold typed text</b> in it";
Console.WriteLine(ToggleRichText(content, "b", 8, 11) + "\n");
Console.WriteLine(ToggleRichText(content, "b", 23, 35) + "\n");
Console.WriteLine(ToggleRichText(content, "b", 11, 56) + "\n");
Console.WriteLine(ToggleRichText(content, "b", 35, 56) + "\n");
Console.WriteLine(ToggleRichText(content, "b", 35, 42) + "\n");
var content2 = "<style=h1>This is a H1</style>";
Console.WriteLine(ToggleRichText(content2, "style", 15, 19, "=h2") + "\n");
var content3 = "<align=left>This is left aligned text, but I want to make this middle bit right aligned, and keep this end bit left aligned</align>";
Console.WriteLine(ToggleRichText(content3, "align", 39, 88, "=right") + "\n");
var content4 = "<color=00>This is colored text, but I want to make</color> <color=11>this middle bit different, and keep this end bit</color>";
Console.WriteLine(ToggleRichText(content4, "color", 31, 84, "=22") + "\n");