在javascript中第n次出现正则表达式时拆分一个字符串

时间:2013-11-01 22:23:00

标签: javascript regex arrays string split

我知道split可以获得第二个参数作为限制,但它不是我想要的。我知道可以通过使用实心字符串分隔符再次拆分和连接来完成。

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

考虑这个字符串:

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 的解决方案,以便在正则表达式的n th 出现时拆分字符串?

1 个答案:

答案 0 :(得分: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

相关问题