Matas Matas - 3 months ago 15
C# Question

How to escape string while programmatically generating markdown table

I use C# to programmatically generate markdown tables from user input.

Edit

Consider this demo code:

var a = Console.ReadLine();
var b = Console.ReadLine();
var c = Console.ReadLine();

var markdownTableBuilder = new StringBuilder();
markdownTableBuilder.AppendLine("| Column A | Column B | Column C |");
markdownTableBuilder.AppendLine("| -------- | -------- | ---------|");

markdownTableBuilder.AppendLine($"| {a} | {b} | {c}");
markdownTableBuilder.AppendLine("");

Console.WriteLine(markdownTableBuilder.ToString());


I want to escape all markdown syntax from a,b,c variables. For example, if user enters something like Hello | *world*, it should be escaped to Hello \| \*world\*

Answer

You can use regex for replacement:

string escaped = Regex.Replace(userInput, @"([|\*])", @"\$1");

This will find any '|', '\', '*' character and put a '\' in front of it.