Matas Matas - 1 year ago 94
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\*

Answer Source

You can use regex for replacement:

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download