简体   繁体   中英

Regex get value between braces inclusive the braces with split

I am trying to build a Regex for a split in Javascript that will split a string on every position where there are braces with text inside {t}.

The problem I have is the Regex expression. At the moment I have a Regex expression that matches the braces {}, but when I split the string on these braces, the braces will have been removed by the split function.

So imagine I have a string: "My name is {name} and I am {years} old". On that String I will use the expression below:

const splitted = value.split(/[{}]+/g); // Value is "My name is {name} and I am {years} old"
console.log(splitted); 

Above console.log shows

["My name is ,", "name", " and I am ", "years", " old"]

But I want

["My name is ,", "{name}", " and I am ", "{years}", " old"]

What am I doing wrong?

You may use this regex with a capture group:

 const s = "My name is {name} and I am {years} old"; var arr = s.split(/({[^}]*})/g); console.log(arr);

{[^}]*} matches a substring that starts with { and ends with } and by putting a capture group around this pattern we ensure that this group is part of the split result.

We can use lazy Quantifier for this.

 const s = "My name is {name} and I am {years} old"; var arr = s.split(/({[^]*?})/g); console.log(arr);

Lazy quantifier *? gives you the shortest match that fits the regex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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