gpt4 book ai didi

javascript - JS Regex - 替换 Markdown 链接的内容

转载 作者:行者123 更新时间:2023-11-29 10:38:58 26 4
gpt4 key购买 nike

我几乎已经解决了一个正则表达式问题,只是一件小事。

我想得到这个:

然后使用 [chalk](#api).red(string[, options])

进入这个:

然后使用 chalk.red(string[, options])

我有这个:

var md = 'and so use chalk.red(string[, options])';
console.log(md.replace(/(\[.*?\]\()(.+?)(\))/g, '$1'))

[x](y) 完美匹配。但是,$1 返回 [chalk](。我希望它返回 chalk,但我不知道如何执行此操作。

我可能(?)已经想通了:

这是否适用于所有情况?

/(\[(.*?)\]\()(.+?)(\))/g

最佳答案

让我们看看你当前的正则表达式做了什么

/(\[(.*?)\]\()(.+?)(\))/g
1st Capturing group (\[(.*?)\]\()
\[ matches the character [ literally
2nd Capturing group (.*?)
.*? matches any character (except newline)
Quantifier: *? Between zero and unlimited times, as few times as possible, expanding as needed [lazy]
\] matches the character ] literally
\( matches the character ( literally
3rd Capturing group (.+?)
.+? matches any character (except newline)
Quantifier: +? Between one and unlimited times, as few times as possible, expanding as needed [lazy]
4th Capturing group (\))
\) matches the character ) literally

如您所见,您的第一个捕获组包含您的第二个捕获组。第二个捕获组是 chalk,第一个捕获组是 [chalk](

  1. 您可以将您的 javascript 更改为读取 console.log(md.replace(/(\[.*?\]\()(.+?)(\))/g, '$2'))
  2. 重写您的正则表达式以删除捕获方括号的括号,这样您就只能捕获其中的内容。 \[(.*?)\]\((.+?)\)

如果您是正则表达式的新手,我强烈建议您使用正则表达式工具(例如 regex101.com)来查看您的组是什么以及您的正则表达式究竟在做什么。

这是我为你保存的正则表达式 https://regex101.com/r/tZ6yK9/1

关于javascript - JS Regex - 替换 Markdown 链接的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32381742/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com