首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >电报Bot 4.5 MarkdownV2上的转义字符给超链接带来了麻烦

电报Bot 4.5 MarkdownV2上的转义字符给超链接带来了麻烦
EN

Stack Overflow用户
提问于 2020-02-08 18:47:36
回答 1查看 5.7K关注 0票数 4

电报Bot 4.5提供了新的解析模式,MarkdownV2。同时,这些_ * [ ] ( ) ~ > # + - = | { } . !字符必须使用前面的字符\进行转义。

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

溶液

代码语言:javascript
复制
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',
    }
  )
});

结果

EN

回答 1

Stack Overflow用户

发布于 2020-02-10 07:08:14

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

代码语言:javascript
复制
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);

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60130062

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档