【问题标题】:Regex to extract the content inside [squarebrackets] but not [[wiki-links]]正则表达式提取 [方括号] 内的内容,但不提取 [[wiki-links]]
【发布时间】:2021-10-19 06:53:05
【问题描述】:

我正在寻找一个正则表达式,它可以匹配和提取 [squarebrackets] 内的内容,但不能匹配和提取 [[wiki-links]] 内的内容。所以对于上面的例子,我将只提取squarebrackets 部分,而不是[squarebrackets][wiki-links]wiki-links

目前,我发现了两个正则表达式:

  1. 仅提取 [[wiki-links]] 内的内容(而不是 [方括号]):
/[^[\]]+(?=]])/g
  1. 提取 [[wiki-links]] 和 [方括号] 中的内容:
\[[^\[\]]+\]/g

第二个接近我想要的,但它仍然包含方括号本身并捕获我不想要的 [[wiki-links]] 内容。

我怎样才能通过修改正则表达式来排除这些,这样我就只能得到单个方括号内的内容,而没有括号本身?

谢谢!

【问题讨论】:

  • 可能是(?<!\[)\[([^\[\]]+)\](?!\])?见regex101.com/r/mkhCX7/2
  • @WiktorStribiżew 这非常接近,但我们也可以从结果中排除[] 吗? :)
  • 但您只需捕获[] 之间的部分,它们就会被排除在外。
  • 是的@WiktorStribiżew 在线程中回复

标签: javascript node.js regex regex-negation


【解决方案1】:

你可以使用

/(?<!\[)\[([^[\]]+)](?!])/g

请参阅regex demo详情

  • (?&lt;!\[) - 一个否定的向后查找,匹配一个没有紧跟在 [ 字符之前的位置
  • \[ - 一个 [ 字符
  • ([^[\]]+) - 第 1 组:除 [] 之外的一个或多个字符
  • ] - 一个 ] 字符
  • (?!]) - 一个 ] 字符。

查看 JavaScript 演示:

const text = "I'm looking for a regex that could match and extract the content inside [squarebrackets] but not inside [[wiki-links]].";
const regex = /(?<!\[)\[([^[\]]+)](?!])/g;
const matches = Array.from(text.matchAll(regex), x => x[1]);
console.log(matches);

如果您将它与旧的 ECMAScript 正则表达式一起使用:

var text = "I'm looking for a regex that could match and extract the content inside [squarebrackets] but not inside [[wiki-links]].";
var regex = /(\[?)\[([^[\]]+)](?!])/g;
var matches = [], m;
while (m = regex.exec(text)) {
  if (m[1] !== undefined) {
    matches.push(m[2]);
  }
}
console.log(matches);

【讨论】:

    猜你喜欢
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 2015-12-10
    • 2020-09-27
    • 2010-11-14
    • 2022-01-17
    • 1970-01-01
    相关资源
    最近更新 更多