regex - Telegram Bot API 4.5 MarkdownV2 上的转义字符给超链接带来麻烦
问题描述
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',
}
)
});
结果
解决方案
为了避免转义格式的链接,[...](http...)
您可以匹配它们并捕获到一个组中,然后匹配所有字符以在其他上下文中转义。然后,检查 Group 1 值,如果它不为空,则替换为 Group 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);
推荐阅读
- php - PHP Rest API 端点函数将回显停止进一步处理
- react-native - 设置 react-native-firebase 后无法运行项目
- javascript - 使用 javascript 切换变量的值
- mysql - 使用 Ansible 更新 Mysql 用户的主机名
- spring - Spring Oauth 似乎没有解码客户端密码
- asp.net-mvc - MVC.Net 表单身份验证
- javascript - 警告:遇到两个孩子使用相同的键,`-`。密钥应该是唯一的,以便组件在更新时保持其身份
- laravel - Undefind withoutExceptionHandling()
- scylla - 从scylla中选择时如何保证timeuuid单调递增
- node.js - 使用 Node.js 应用程序在 Active Directory 中执行搜索查询