简体   繁体   中英

Split by space, preserve curly brackets but include spaces

I have a string containing a pattern and trying to split this value by space, preserve any spaces inside groups with curly brackets and also preserve the spaces.

Unfortunately my spaces are getting filtered out in the process as well. Is there a way I can preserve them in the process?

            var val = "{dimension} {equals,does not equal,contains,does not contain} {value}";
            var re = /\s*(\{[a-zA-Z0-9]+\})\s*/g;
            var split = val.split(re).filter(Boolean);
            console.log('split',split);

Current output: ["{dimension}", "{equals,does not equal,contains,does not contain}", "{value}"]

Expected output: ["{dimension}", " ", "{equals,does not equal,contains,does not contain}", " ", "{value}"]

You can use

 var val = "{dimension} {equals,does not equal,contains,does not contain} {value}"; console.log(val.match(/{[^{}]*}|[^\s{]+|\s+/g));

See the regex demo .

Details :

  • {[^{}]*} - a { , then zero or more chars other than { and }
  • | - or
  • [^\s{]+ - zero or more chars other than whitespace and {
  • | - or
  • \s+ - one or more whitespace chars.

I think this (?<=[\}])(\s) work as well:

 var val = "{dimension} {equals,does not equal,contains,does not contain} {value}"; var re = /(?<=[\}])(\s)/gi; var split = val.split(re).filter(Boolean); console.log('split',split);

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