![](/img/trans.png)
[英]Write a Regex to find all words in a string which are enclosed by brackets
[英]Regex to fetch all spaces as long as they are not enclosed in brackets
正则表达式获取所有空格,只要它们不包含在大括号中
这是针对 javascript 提及系统
例如:“说@::{Joseph Empyre}{b0268efc-0002-485b-b3b0-174fad6b87fc},好吗?”
需要获得:
[ "说 ", "@::{Joseph Empyre}{b0268efc-0002-485b-b3b0-174fad6b87fc}", ",", "所有", "对吗?" ]
[编辑]
解决于: https://codesandbox.io/s/rough-http-8sgk2
对不起,我的英语不好
我将您的问题解释为您所说to fetch all spaces as long as they are not enclosed in braces
,尽管您的结果示例不是我所期望的。 您的示例结果在 speak 之后包含一个空格,以及在{}
组之后为,
单独匹配。 下面我的 output 显示了我对您所要求的内容的期望,即仅在大括号外的空格上拆分的字符串列表。
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?"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.