正则表达式:在我的标签内抓取文本

Regex: Grab text inside my tag

我正在研究 NodeJS 读取文件中的文本,但我不太了解用于抓取字符串的正则表达式,所以我寻求帮助。

示例文本:

text text {{ 'translate me' | lang }} text {{ 'A' | replace('A', 'B') }} {{"another text"|lang}}

我只想在里面抓取文本 {{ 'SOMETHING' |郎}}

输出

['translate me', 'another text']

那么,如何使用正则表达式进行抓取,谢谢。

哦,它还应该支持一些间距大小写,比如

还支持 " 和 '(单引号和双引号)

两个开头的大括号,后跟零个或多个空格,后跟引用的字符串,后跟零个或多个空格,然后是 |lang 和两个结束的大括号,使用 (new ) 回顾:

const text = "text text {{ 'translate me' | lang }} text {{ 'A' | replace('A', 'B') }} {{ 'another text' | lang }}";
console.log(text.match(
  /(?<=\{\{ *')[^']+(?=' *\| *lang *}})/g
));

// or, without lookbehind:

const re = /\{\{ *'([^']+)(?=' *\| *lang *}})/g;
let match;
const matches = [];
while ((match = re.exec(text)) !== null) {
  matches.push(match[1]);
}
console.log(matches);