【问题标题】:JS Regex - replace contents of markdown linkJS Regex - 替换markdown链接的内容
【发布时间】:2015-09-03 17:12:34
【问题描述】:

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

我想得到这个:

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,但我不知道该怎么做。

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

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

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

【问题讨论】:

  • 我很困惑,你的前后字符串是一样的
  • 哎呀你是对的。
  • this的可能重复

标签: javascript regex


【解决方案1】:

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

/(\[(.*?)\]\()(.+?)(\))/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

【讨论】:

    【解决方案2】:

    使用这个正则表达式:

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

    如果你这样称呼它

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

    它返回这个

    "等使用 chalk.red(string[, options])"

    【讨论】:

      猜你喜欢
      • 2021-07-01
      • 2015-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      相关资源
      最近更新 更多