简体   繁体   English

使用正则表达式拆分在数组中创建2个空元素

[英]Split using regex creates 2 empty elements in array

I need to split a string into 2 pieces using regex, so I used the following code: 我需要使用正则表达式将字符串分成2部分,因此我使用了以下代码:

var str = "This is a test";
var list = str.split(/(test)/);

Required output: 要求的输出:

list = ["This is a ", "test"]

Instead of 2 this gives me 3 elements in the array (last one is empty). 而不是2,这给了我数组中的3个元素(最后一个为空)。 I understand that regex finds nothing after the 2nd match so it adds an empty (3rd) element. 我知道正则表达式在第二场比赛之后一无所获,因此它添加了一个空的(第三场)元素。 Is there any way that I can modify my code so I get exactly 2 elements thus avoiding the last empty element? 有什么办法可以修改我的代码,以便我得到2个元素,从而避免最后一个空元素?

Note: the above code is a simplified version for which we can use other options besides regex but I would have to use regex. 注意:以上代码是简化版本,除正则表达式外,我们还可以使用其他选项,但我必须使用正则表达式。

var str = "This is a test";

var list = str.split(/(test)/,2);

list: ["This is a ", "test"] 列表: ["This is a ", "test"]

Perhaps overkill if you can guarantee that you are only expecting an array of length two but given the nature of the question a more robust solution may be to use Array.filter to remove all empty strings from the array - including entries in the middle of the array which would arise from several delimiters appearing next to each other in your input string. 如果您可以保证只期望长度为2的数组,但可能会Array.filter ,但是考虑到问题的性质,更可靠的解决方案是使用Array.filter从数组中删除所有空字符串-包括中间的条目。数组,该数组由输入字符串中彼此相邻出现的多个定界符引起。

var list = str.split(/(test)/).filter(
    function(v){ return v!=null && v!='' }
);

You can try with checking if last element is empty or not: 您可以尝试检查last元素是否为空:

var last = list.pop();
    last.length || list.push(last);

or: 要么:

list[list.length-1].length || list.pop();

or even shorter: 甚至更短:

list.slice(-1)[0].length || list.pop();

To handle first empty element ( test was there as @Kobi suggested) use: 要处理第一个空元素(如@Kobi建议的那样进行test was there ),请使用:

list[0].length || list.shift();

This is giving me the results you want: 这给了我您想要的结果:

var str = "This is a test";
var list = str.split(/(?=test)/g);

(?= is a lookahead, it doesn't capture the word test so that stays in the array after splitting. (?=是前瞻性的,它不捕获单词test因此在拆分后保留在数组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM