2013-11-01 44 views
1

正则表达式的第n次出现的字符串,我知道split可以得到第二个参数的限制,但它不是我要找的。我知道这可以通过分割并再次连接一个固定的字符串分隔符来完成。拆分在JavaScript的

的问题是分隔符是一个正则表达式,我不知道,匹配模式的精确长度。

考虑这个字符串:

this is title 
-------------------------- 
rest is body! even if there is some dashes.! 
-------- 
--------------------- 
it should not counted as a separated part! 

通过使用这样的:

str.split(/---*\n/); 

我会得到:

[ 
    'this is title', 
    'rest is body! even if there is some dashes.!', 
    '', 
    'it should not counted as a separated part!' 
] 

而这正是我想要的:(如果我想通过第一次出现

分裂
[ 
    'this is title', 
    'rest is body! even if there is some dashes.!\n--------\n---------------------\nit should not counted as a separated part!' 
] 

该解决方案是什么,我现在有,但它只是在第一次出现。

function split(str, regex) { 
    var match = str.match(regex); 
    return [str.substr(0, match.index), str.substr(match.index+match[0].length)]; 
} 

任何想法如何概括为任意数量ň分割第n个发生正则表达式的字符串的解决方案?

回答

3
var str= "this-----that---these------those"; 
var N= 2; 
var regex= new RegExp("^((?:[\\s\\S]*?---*){"+(N-1)+"}[\\s\\S]*?)---*([\\s\\S]*)$"); 
var result= regex.exec(str).slice(1,3); 
console.log(result); 

输出:

["this-----that", "these------those"] 

jsFiddle
选项与功能:

var generateRegExp= function (N) { 
    return new RegExp("^((?:[\\s\\S]*?---*){"+(N-1)+"}[\\s\\S]*?)---*([\\s\\S]*)$"); 
}; 

var getSlice= function(str, regexGenerator, N) { 
    return regexGenerator(N).exec(str).slice(1,3); 
}; 

var str= "this-----that---these------those"; 
var N= 2; 
var result= getSlice(str, generateRegExp, N); 
console.log(result); 

jsFiddle

选项与功能2:

var getSlice= function(str, regex, N) { 
    var re= new RegExp("^((?:[\\s\\S]*?"+regex+"){"+(N-1)+"}[\\s\\S]*?)"+regex+"([\\s\\S]*)$"); 
    return re.exec(str).slice(1,3); 
}; 

var str= "this-----that---these------those"; 
var N= 3; 
var result= getSlice(str, "---*", N); 
console.log(result); 

jsFiddle

+0

感谢。 这比我更好的解决方案,但我正在寻找一个解决方案由一个正则表达式的第n次出现分裂的字符串。您的解决方案仅在第一次出现时拆分字符串。 –

+0

埃米尔,举例说明源文本和第N次出现(N = 2或更多)情况下的结果。 – ReinRaus

+0

想象一下这个字符串:'this ----- that --- these ------ those'。如果N = 2(1型)时,结果应该是:[“这个-----即”,“这些------那些”] –