使用正则表达式获取双花括号中的值

3

From this string:

dfasd {{test}} asdhfj {{te{st2}} asdfasd {{te}st3}}

我想获得以下子字符串:
test, te{st2, te}st3

换句话说,我想将一切内容保留在双花括号中,包括单花括号。对于此模式,我无法使用:
{{(.*)}}

因为它匹配了第一个 {{ 和最后一个 }} 之间的所有内容。
test}} asdhfj {{te{st2}} asdfasd {{te}st3

我使用以下正则表达式模式获得了前两个:

{{([^}]*)}}

有没有使用正则表达式获取所有三个的方法?

1
Try {{(.*?)}} - ctwheels
2个回答

12

尝试使用{{(.*?)}}

.*?表示进行懒惰/非贪婪搜索=>一旦}}匹配,它将捕获找到的文本并停止查找。否则,它将进行贪婪搜索,因此从第一个{{开始,并以最后一个}}结束。


2
.*? 不是贪婪的。它是懒惰的:只要有机会,它就会停止。 - ctwheels
感谢您的答案和解释。这个模式确实符合我的要求。 - eugenesqr

2

这不太美观,但它不使用正则表达式,并清晰地说明了您想要实现的目标。

const testString = 'dfasd {{test}} asdhfj {{te{st2}} asdfasd {{te}st3}}';

const getInsideDoubleCurly = (str) => str.split('{{')
  .filter(val => val.includes('}}'))
  .map(val => val.substring(0, val.indexOf('}}')));

console.log(getInsideDoubleCurly(testString));


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接