Skip to content

Instantly share code, notes, and snippets.

@tuscen
Last active March 17, 2018 15:44
Show Gist options
  • Select an option

  • Save tuscen/79087ed4ac53f24f2fe5285e702ac241 to your computer and use it in GitHub Desktop.

Select an option

Save tuscen/79087ed4ac53f24f2fe5285e702ac241 to your computer and use it in GitHub Desktop.
Escape markdown tokens for Telegram markdown markup
// Does it work properly with utf16 encoded strings (utf16 is used in .NET internally)
// considering that its length is two bytes and strings are iterated char by char?
public static class StringExtensions
{
private static char[] EscapableChars = { '*', '_', '[', '`', '\\', ']' };
public static string EscapeMarkdown(this string value)
=> string.Join(
string.Empty,
value.Select(
character => EscapableChars.Contains(character)
? $"\\{character}"
: $"{character}"));
}
// Regex version
public static class StringExtensions
{
public static string EscapeMarkdown(this string input)
=> Regex.Replace(
input,
"(?<token>[*_\\\\`\\\\[\\]])",
m => $"\\{m.Groups["token"].Value}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment