2013-11-01 92 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型)時,結果應該是:[「這個-----即」,「這些------那些」] –