如何用正则将Markdown裸链转为链接且不匹配已格式化链接
问题原因
你当前正则出现误匹配的核心原因是仅排除了直接跟在](后的链接目标URL,没有排除位于[]内部作为链接文本的URL,刚好你的测试用例中格式化链接的文本本身就是URL,所以被误匹配。
修复方案
NodeJS基于V8引擎,支持可变长度的负向后行断言,使用以下正则即可满足需求:/(?<!\[[^\]]*?)(?<!\]\([^)]*?)\b(https?|ftp):\/\/[A-Z0-9+&@#\/%?=~_|!:,.;-]*[A-Z0-9+&@#\/%=~_|]/gim
正则规则说明
(?<!\[[^\]]*?):负向后行断言,排除所有位于闭合方括号[]内部的URL,避免匹配格式化链接的文本部分(?<!\]\([^)]*?):优化原有规则,排除所有位于链接目标括号()内部的URL,避免匹配格式化链接的目标部分- 后续部分保持原有URL匹配逻辑不变,兼容http/https/ftp协议的FQDN链接
代码示例
const rawMd = `Login in to My site [https://example.com/](https://example.com/) and select Something > Select below details further. (https://example.com/abc/1.html) Also have a look at https://example.com/abc/1.html`; const nakedUrlRegex = /(?<!\[[^\]]*?)(?<!\]\([^)]*?)\b(https?|ftp):\/\/[A-Z0-9+&@#\/%?=~_|!:,.;-]*[A-Z0-9+&@#\/%=~_|]/gim; const formattedMd = rawMd.replace(nakedUrlRegex, url => `[${url}](${url})`);
运行结果
格式化后文本仅对两个裸链接做转换,原有格式化链接保持不变:
Login in to My site [https://example.com/](https://example.com/) and select Something > Select below details further. ([https://example.com/abc/1.html](https://example.com/abc/1.html)) Also have a look at [https://example.com/abc/1.html](https://example.com/abc/1.html)
内容的提问来源于stack exchange,提问作者Birla
相关产品推荐
相关产品推荐

