0

Say I have a string - [H*la.Am!go] and I want to replace all the characters specified in the character set with that character appended after "\"

Character set- ['_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!','\']

So the output would be -

\\[H\\*la\\.Am\\!go\\]

I can go about doing this chaining replace() method like so:

str.replace('[','\\[').replace('_','\\_')...

But this searches the string repeatedly for characters, thereby inefficient and also the code isn't clean.

Could someone help me out in implementing the regex replacement for this please?

  • Your “character set” is almost but not quite the Regex metacharacters, and `\\` is the Regex escape character. Are you trying to [escape metacharacters in a Regex](https://stackoverflow.com/questions/3561493/)? If you are [you should have told us that](https://meta.stackexchange.com/questions/66377/). – Dour High Arch Jun 09 '20 at 00:51
  • @DourHighArch Thank you for your reply, and the suggested answer works fine for my case, except a few characters which needed to be added. Actually these are the characters that need to be escaped when using **MarkdownV2** in telegram bot-development. – jasondoyle121 Jun 09 '20 at 04:21

0 Answers0