【问题标题】:Escaped character on Telegram Bot API 4.5 MarkdownV2 gives trouble for hyper linkTelegram Bot API 4.5 MarkdownV2 上的转义字符给超链接带来麻烦
【发布时间】:2020-02-08 18:47:36
【问题描述】:

Telegram Bot API 4.5 带有新的解析模式 MarkdownV2。同时这些_ * [ ] ( ) ~ > # + - = | { } . ! 字符必须用前面的字符\ 进行转义。

.replace(/[-.+?^$[\](){}\\]/g, '\\$&') 用作添加转义字符的解决方案,效果很好,但不幸的是,此解决方案确实影响超链接方法[inline URL](http://www.example.com/),因为它替换了\[inline URL\]\(http://www.example\.com/\)

解决方案

bot.on('text', (ctx) => {
  const { chat } = ctx.message;
  const msgs = `Here is the [rules](https://telegra.ph/rules-05-06) Please read carefully and give the details which mentioned below.
*Name:*
*Place:*
*Education:*
*Experience:*
You can also call me on (01234567890)
__For premium service please contact with admin__`;

  const msgmsgWithEscape = msgs.replace(/[-.+?^$[\](){}\\]/g, '\\$&')

  ctx.telegram.sendMessage(
    chat.id,
    msgmsgWithEscape,
    {
      parse_mode: 'MarkdownV2',
    }
  )
});

结果

【问题讨论】:

    标签: regex replace escaping telegram telegram-bot


    【解决方案1】:

    为避免转义格式为[...](http...) 的链接,您可以匹配它们并捕获到一个组中,然后匹配所有字符以在其他上下文中转义。然后,检查第 1 组的值,如果它不为空,则替换为第 1 组的值,否则,替换为转义字符:

    const msgs = `Here is the [rules](https://telegra.ph/rules-05-06) Please read carefully and give the details which mentioned below.
    *Name:*
    *Place:*
    *Education:*
    *Experience:*
    You can also call me on (01234567890)
    __For premium service please contact with admin__`;
    
    const msgmsgWithEscape = msgs.replace(/(\[[^\][]*]\(http[^()]*\))|[_*[\]()~>#+=|{}.!-]/gi,
        (x,y) => y ? y : '\\' + x)
    
    console.log(msgmsgWithEscape);

    【讨论】:

    • 您应该在正则表达式中添加 !#:'_', '*', '[', ']', ' (', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.' ,'!'必须转义
    • @LeeTwelve 我认为主要的问题是匹配括号内字符串之外的那些字符,但你是对的。我添加了缺少的字符。
    • 您应该添加一个预处理链接标题的步骤。类似msgmsgWithEscape = msgmsgWithEscape.replace(/\[([^\][]*)]\(/g, (x,y) => "[" + y.replace(/[-.+?^$[\](){}\\!#]/g, '\\$&') + "]\(" );
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-27
    相关资源
    最近更新 更多