Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Regex to for.split()分隔除引号以外的空格上的字符串_Javascript_Regex - Fatal编程技术网

Javascript Regex to for.split()分隔除引号以外的空格上的字符串

Javascript Regex to for.split()分隔除引号以外的空格上的字符串,javascript,regex,Javascript,Regex,可以使用正则表达式将字符串拆分为空格和引号吗?出于性能原因,我只能使用.split()而不是.match() 例如: 'This is an "example for" stack overflow.' 输出: ["This", "is", "an", "example for", "stack", "overflow"] 对您的问题的简短回答是肯定的,您可以在String.prototype.split()中使用正则表达式。 这是基于您的示例所需的代码: 'This is an "exam

可以使用正则表达式将字符串拆分为空格和引号吗?出于性能原因,我只能使用
.split()
而不是
.match()

例如:

'This is an "example for" stack overflow.'
输出:

["This", "is", "an", "example for", "stack", "overflow"]

对您的问题的简短回答是肯定的,您可以在String.prototype.split()中使用正则表达式。 这是基于您的示例所需的代码:

'This is an "example for" stack overflow.'.split(/\"\s|\s\"|\s|\"/g);

使用此正则表达式,您可以更轻松地在令牌中捕获字符串,而不是拆分字符串,或者捕获一个纯单词,或者捕获一个包含空格但包含在双引号内的单词

"([\w ]*?)"|\w+
下面是相同的示例Javascript代码

var s='这是“堆栈溢出”的一个“示例”;
变量re=/“([\w]*?)”|\w+/g;
var-arr=[];
做{
m=执行董事;
如果(m){
if(m[1]){
arr.push(m[1]);
}else如果(m[0]){
arr.push(m[0]);
}
}
}while(m);

控制台日志(arr)“出于性能原因,我只能使用.split()而不是.match()。”嗯?你能把这一点再详细一点吗?还有,你对这方面的研究发现了什么?转义引号呢?你尝试过什么样的事情?这听起来很矛盾。如果你可以使用正则表达式,那么这比使用
str.match(re)
更好吗?或者如果你不能使用str.match(re)
,那么正则表达式似乎是不可能的。和
.split()
不支持正则表达式。这会给出错误的输出结果,因为它甚至会在双引号内按空格分割<代码>[“This”、“is”、“an”、“example”、“for”、“stack”、“overflow.”]