Last active
March 17, 2018 15:44
-
-
Save tuscen/79087ed4ac53f24f2fe5285e702ac241 to your computer and use it in GitHub Desktop.
Escape markdown tokens for Telegram markdown markup
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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}")); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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