Matas Matas - 7 months ago 45
C# Question

How to escape string while programmatically generating markdown table

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


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}");


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\*


You can use regex for replacement:

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

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