【问题标题】:JavaScript regular expression to catch [boxes]用于捕获 [boxes] 的 JavaScript 正则表达式
【发布时间】:2018-09-18 04:01:31
【问题描述】:

所以我正在使用城市词典 api,他们的术语可以使用 [term] 和 api 链接到其他人,你会得到我想在 markdown 中让它们实际超链接的框,即term 所以我尝试制作一个替换正则表达式要做到这一点,到目前为止我做得很好,除了当盒子有多个单词(如 [空格词])时它不起作用我一直试图找到一个好的正则表达式来匹配它,但它最终匹配整个字符串这是正则表达式我用的很好,但没有空格

"example [string] with [some] boxes".replace(/(\[(\S+)\])/ig, "$1(https://www.urbandictionary.com/define.php?term=$2)");

【问题讨论】:

  • 试试/(\[([^\][]+)\])/g,例如.replace(/\[([^\][]+)\]/g, "$&(https://www.urbandictionary.com/define.php?term=$1)")。顺便说一句,空格不应该替换为+吗?然后查看.replace(/\[([^\][]+)\]/g, (x,y) => x + "(https://www.urbandictionary.com/define.php?term=" + y.replace(/\s+/g, "+") + ")")
  • 哦,可以了,谢谢
  • ([\w\s]+) 替换你的(\S+) 工作正常

标签: javascript regex


【解决方案1】:

您可以使用/(\[([^\][]+)])/g 正则表达式并替换为"$&(https://www.urbandictionary.com/define.php?term=$1)"

console.log(
      "example [string] with [space words] boxes".replace(
         /\[([^\][]+)]/g, "$&(https://www.urbandictionary.com/define.php?term=$1)")
    );

如果空格应该替换为+,您可以使用

console.log(
  "example [string] with [space words] boxes".replace(
     /\[([^\][]+)]/g, (x,y) => 
     x + "(https://www.urbandictionary.com/define.php?term=" + y.replace(/\s+/g, "+") + ")")
);

请注意,您无需将整个模式包含在捕获组中,您始终可以在替换模式中的 $& 占位符的帮助下访问整个匹配值。因此,建议的模式中只有一个(...)

模式详情

  • \[ - 一个 [ 字符
  • ([^\][]+) - 捕获组 1:除 [] 之外的任何一个或多个字符(注意 [ 不必在字符类中转义,但 ] 必须)
  • ] - 一个 ] 字符(请注意,在字符类之外 ] 不必转义)。

【讨论】:

    猜你喜欢
    • 2012-03-20
    • 2017-02-10
    • 1970-01-01
    • 2022-07-29
    • 2019-01-27
    • 2016-02-10
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多