I had the displeasure recently of needing to generate HTML that would eventually be exported/saved as a .docx (Word) document. Part of the source of the HTML was a rich text editor and something along the path was converting my specified hex color values (#fff, etc.) into their rgba equivalents. The problem is that Word (which sucks with HTML) doesn't recognize rgba values so I really needed those to stay hex. It turns out you can just write a method for that. Well, Claude can. I can't. But I can copy Claude's method and understand it. Which I did. Here it is.
private static readonly Regex RgbRegex = new(@"rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*[\d.]+\s*)?\)", RegexOptions.Compiled | RegexOptions.IgnoreCase);I just make sure the HTML runs through their during save and my hex values persist. Beautiful.
private static string ConvertRgbToHex(string style) { return RgbRegex.Replace(style, m => { int r = int.Parse(m.Groups[1].Value); int g = int.Parse(m.Groups[2].Value); int b = int.Parse(m.Groups[3].Value); return $"#{r:X2}{g:X2}{b:X2}"; }); }
No comments:
Post a Comment