JS Regex -替换markdown链接的内容

JS Regex - replace contents of markdown link

本文关键字:链接 markdown Regex 替换 JS      更新时间:2023-09-26

我几乎找到了一个正则表达式问题,只是一件小事。

我正在尝试得到这个:

and so use [chalk](#api).red(string[, options])

这:

and so use chalk.red(string[, options])

我有这个:

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

[x](y)完全匹配。但是,$1返回[chalk](。我希望它返回chalk而不是,我对如何做到这一点感到困惑。

I might(?) have figure out:

这在所有情况下都有效吗?

/('[(.*?)']'()(.+?)('))/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. 重写你的正则表达式,删除捕获括号的圆括号,这样你只捕获它们里面的东西。'[(.*?)']'((.+?)')

如果你是正则表达式的新手,我强烈推荐一个regex工具,比如regex101.com,看看你的组是什么,你的regex到底在做什么。

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

使用此RegExp:

/'[([^']]+)'][^')]+')/g

如果你叫它

'and so use [chalk](#api).red(string[, options])'.replace(/'[([^']]+)'][^')]+')/g, '$1')

它返回这个

"所以用粉笔。红色(string[选项])"