简体   繁体   English

使用正则表达式在双花括号内获取值

[英]Get values inside double curly braces with regex

From this string: 从此字符串:

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

I would like to get the following substrings: 我想获得以下子字符串:

test, te{st2, te}st3

In other words I want keep everything inside double curly braces including single curly braces . 换句话说,我想将所有内容都保留在双大括号内, 包括单大括号内

I can't use this pattern: 我不能使用这种模式:

{{(.*)}}

because it matches the whole thing between first {{ and last }}: 因为它匹配前{{和last}}之间的整个内容:

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

I managed to get the first two with this regex pattern: 我设法用此正则表达式模式获得了前两个:

{{([^}]*)}}

Is there any way to get all three using regex? 有什么办法可以使用正则表达式来获取全部三个?

Try {{(.*?)}} . 尝试{{(.*?)}}

.*? means to do a lazy / non greedy search => as soon as }} matches, it will capture the found text and stop looking. 意味着在}}匹配后立即进行一次懒惰/非贪婪搜索=>,它将捕获找到的文本并停止查找。 Otherwise it will do a greedy search and therefore start with the first {{ and end with the very last }}. 否则,它将进行贪婪的搜索,因此从第一个{{开始,最后一个}}开始。

This isn't that pretty, but it doesn't use RegEx and makes it clear what you are trying to accomplish. 这不是那么漂亮,但是它不使用RegEx,并且可以清楚地说明您要完成的工作。

 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)); 

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

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