为什么正则表达式没有应用于最终输出?

问题描述 投票:0回答:1

我正在尝试将一些正则表达式应用于使用笔记程序 Obsidian 的 Dataview 插件收集的一些文本。

我正在使用 dataview 插件从多个笔记中获取一些文本并将其复制为纯文本,然后我获取该文本并使用正则表达式对其进行格式化。我遇到的问题是最终输出的格式不正确,我不知道为什么。

输出示例

输出应该只有“- example”,没有重复的文本和括号

const inputSentences = [
"- [[Note example 3.md|Note example 3]]",
"- [[Note example 2.md|Note example 2]]",
"- [[Note example 1.md|Note example 1]]"
]


function transformSentence(input) {
  if (typeof input !== 'string') {
    // Handle non-string input, e.g., return input as is or throw an error
    return input;
  }
  const regex = /-\s*\[\[([^|]+)\|[^]]+\]\]/g;
  return input.replace(regex, '- $1');
}

inputSentences.forEach(inputSentence => {
  const outputSentence = transformSentence(inputSentence);
  console.log(outputSentence);
})

javascript regex dql dataview obsidian
1个回答
0
投票

你忘记在你的字符集中转义

]

/-\s*\[\[([^|]+)\|[^\]]+\]\]/g
                    ^

使用mplungjan的最小可重现示例:

const inputSentences = [
"- [[Note example 3.md|Note example 3]]",
"- [[Note example 2.md|Note example 2]]",
"- [[Note example 1.md|Note example 1]]"
]


function transformSentence(input) {
  if (typeof input !== 'string') {
    // Handle non-string input, e.g., return input as is or throw an error
    return input;
  }
  const regex = /-\s*\[\[([^|]+)\|[^\]]+\]\]/g;
  return input.replace(regex, '- $1');
}

inputSentences.forEach(inputSentence => {
  const outputSentence = transformSentence(inputSentence);
  console.log(outputSentence);
})

© www.soinside.com 2019 - 2024. All rights reserved.