简体   繁体   English

Javascript - 使用正则表达式在字符串中查找多次出现的模式

[英]Javascript - Use regex to find multiple occurrences of a pattern in a string

I have a string in this format我有一个这种格式的字符串

"{{abc}}, {{def}}, some text {{ghi}}, some other text {{jkl}}"

And I would like to replace each of {{...}} with some string based on what is ... (that comes out of json and not an issue) and stuck with what regex pattern to use.我想用一些基于什么的字符串来替换每个{{...}} ... (来自 json 而不是问题)并坚持使用什么正则表达式模式。 Closest I could come was to /{{(.*)}}/gi , but that returns the whole string as the same has {{ and }} at ends.我能来的最接近的是/{{(.*)}}/gi ,但这会返回整个字符串,因为它的末尾有{{}} Here's the code I have tried这是我试过的代码

let str = "{{abc}}, {{def}}, some text {{ghi}}, some other text {{jkl}}";
let regex = /{{(.*)}}/gi;
let result;
let indices = [];
let results = [];
while ((result = regex.exec(str))) {
    indices.push(result.index);
    results.push(result[0]);
}

Any help will be highly appreciated任何帮助将不胜感激

This will do it: \\{\\{(.*?)\\}\\}这样做: \\{\\{(.*?)\\}\\}

You need to escape the } via \\ , also set the non greedy operator ?您需要通过\\转义} ,还需要设置非贪婪运算符?

See: https://regex101.com/r/F9xdgx/2参见: https : //regex101.com/r/F9xdgx/2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM