Matas
Matas

Reputation: 860

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

Upvotes: 3

Views: 1821

Answers (1)

grek40
grek40

Reputation: 13448

You can use regex for replacement:

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

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

Upvotes: 3

Related Questions