【发布时间】:2016-06-15 14:37:56
【问题描述】:
来自 Mozilla 开发者网络的功能 split():
split() 方法返回新数组。
找到后,从字符串和子字符串中删除分隔符 在数组中返回。如果未找到或省略分隔符,则 数组包含一个由整个字符串组成的元素。如果 分隔符是一个空字符串,str转换为一个数组 字符。
如果分隔符是一个包含捕获的正则表达式 括号,然后每次匹配分隔符,结果 (包括任何未定义的结果)的捕获括号是 拼接到输出数组中。但是,并非所有浏览器都支持此功能 能力。
举个例子:
var string1 = 'one, two, three, four';
var splitString1 = string1.split(', ');
console.log(splitString1); // Outputs ["one", "two", "three", "four"]
这是一个非常干净的方法。我用一个正则表达式和一个稍微不同的字符串尝试了同样的方法:
var string2 = 'one split two split three split four';
var splitString2 = string2.split(/\ split\ /);
console.log(splitString2); // Outputs ["one", "two", "three", "four"]
这与第一个示例一样有效。在以下示例中,我再次更改了字符串,使用了 3 个不同的分隔符:
var string3 = 'one split two splat three splot four';
var splitString3 = string3.split(/\ split\ |\ splat\ |\ splot\ /);
console.log(splitString3); // Outputs ["one", "two", "three", "four"]
但是,正则表达式现在变得相对混乱。我可以对不同的分隔符进行分组,但是结果将包括这些分隔符:
var string4 = 'one split two splat three splot four';
var splitString4 = string4.split(/\ (split|splat|splot)\ /);
console.log(splitString4); // Outputs ["one", "split", "two", "splat", "three", "splot", "four"]
所以我尝试在离开组时从正则表达式中删除空格,但没有多大用处:
var string5 = 'one split two splat three splot four';
var splitString5 = string5.split(/(split|splat|splot)/);
console.log(splitString5);
虽然,当我删除正则表达式中的括号时,分隔符在拆分字符串中消失了:
var string6 = 'one split two splat three splot four';
var splitString6 = string6.split(/split|splat|splot/);
console.log(splitString6); // Outputs ["one ", " two ", " three ", " four"]
另一种方法是使用match() 过滤掉分隔符,但我不太了解反向前瞻的工作原理:
var string7 = 'one split two split three split four';
var splitString7 = string7.match(/((?!split).)*/g);
console.log(splitString7); // Outputs ["one ", "", "plit two ", "", "plit three ", "", "plit four", ""]
它与开头的整个单词不匹配。老实说,我什至不知道这里到底发生了什么。
如何在结果中不包含分隔符的情况下使用正则表达式正确拆分字符串?
【问题讨论】:
-
或许
string5.split(/\s?(split|splat|splot)\s?/) -
如您所见,您不需要(也不想要)该组。因此,要将空格作为分隔符,您可以在每个交替中输入它们 -
/ split | splat | splot /
标签: javascript regex split