【问题标题】:Regex to fetch all spaces as long as they are not enclosed in brackets正则表达式获取所有空格,只要它们不包含在括号中
【发布时间】:2020-01-22 11:57:30
【问题描述】:

正则表达式获取所有空格,只要它们不包含在大括号中

这是一个 javascript 提及系统

例如:“说@::{Joseph Empyre}{b0268efc-0002-485b-b3b0-174fad6b87fc},好吗?”

需要得到:

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

[编辑]

已解决:https://codesandbox.io/s/rough-http-8sgk2

对不起我的英语不好

【问题讨论】:

  • 您应该扩展您的问题,使用当前代码添加对您不起作用并提供更多场景。
  • 我认为这种类型的正则表达式可能无法通过 JavaScript 的正则表达式实现。与使用 RegEx 相比,您自己解析字符串可能会更好。我相信你需要使用消极/积极的观察后/前,其中一些在 JavaScript 中是不可能的。

标签: javascript regex reactjs ecmascript-6 regex-negation


【解决方案1】:

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

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)

控制台:

["Speak", "@::{Joseph Empyre}{b0268efc-0002-485b-b3b0-174fad6b87fc},", "all", "right?"]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 2013-06-17
    相关资源
    最近更新 更多