首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >读取所有空格,只要它们不包含在括号中。

读取所有空格,只要它们不包含在括号中。
EN

Stack Overflow用户
提问于 2019-09-22 00:10:22
回答 1查看 58关注 0票数 0

读取所有空格,只要它们不被大括号包围。

这是一个javascript提到系统。

例句:“说话”:{约瑟夫Empyre}{b0268efc-0002-485b-b3b0-174fad6b87fc},还好吗?“

需要:

“说",”@:{约瑟夫Empyre}{b0268efc-0002-485b-b3b0-174fad6b87fc}",“全部",”对吗?“

编辑

解题于:https://codesandbox.io/s/rough-http-8sgk2

抱歉,我的英语不好

EN

回答 1

Stack Overflow用户

发布于 2019-09-22 01:57:33

正如您对to fetch all spaces as long as they are not enclosed in braces所说的那样,我解释了您的问题,尽管您的结果示例与我所期望的不一样。您的示例结果包含一个在交谈后的空格,以及,{}组之后的单独匹配。下面的输出显示了我对您所要求的内容的期望,在大括号外的空格上拆分的字符串列表。

代码语言:javascript
复制
const str =
    "Speak @::{Joseph Empyre}{b0268efc-0002-485b-b3b0-174fad6b87fc}, all right?";

// This regex matches both pairs of {} with things inside and spaces
// It will not properly handle nested {{}}
// It does this such that instead of capturing the spaces inside the {},
// it instead captures the whole of the {} group, spaces and all,
// so we can discard those later
var re = /(?:\{[^}]*?\})|( )/g;
var match;
var matches = [];
while ((match = re.exec(str)) != null) {
  matches.push(match);
}

var cutString = str;
var splitPieces = [];
for (var len=matches.length, i=len - 1; i>=0; i--) {
  match = matches[i];
  // Since we have matched both groups of {} and spaces, ignore the {} matches
  // just look at the matches that are exactly a space
  if(match[0] == ' ') {
    // Note that if there is a trailing space at the end of the string,
    // we will still treat it as delimiter and give an empty string
    // after it as a split element
    // If this is undesirable, check if match.index + 1 >= cutString.length first
    splitPieces.unshift(cutString.slice(match.index + 1));
    cutString = cutString.slice(0, match.index);
  }
}
splitPieces.unshift(cutString);
console.log(splitPieces)

控制台:

代码语言:javascript
复制
["Speak", "@::{Joseph Empyre}{b0268efc-0002-485b-b3b0-174fad6b87fc},", "all", "right?"]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58045067

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档