我知道 split
可以获取第二个参数作为限制,但这不是我想要的。我知道这可以通过使用实心字符串分隔符再次拆分和连接来完成。
问题是分隔符是正则表达式,我不知道匹配的模式的确切长度。
考虑这个字符串:
this is a title
--------------------------
rest is body! even if there are some dashes!
--------
---------------------
it should not be counted as a separated part!
通过使用这个:
str.split(/---*\n/);
我会得到:
[
'this is a title',
'rest is body! even if there are some dashes.!',
'',
'it should not be counted as a separated part!'
]
这就是我想要的:(如果我想按第一次出现分割)
[
'this is a title',
'rest is body! even if there are some dashes.!\n--------\n---------------------\nit should not be 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 次正则表达式出现时分割字符串,有什么想法吗?
最佳答案
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);
具有功能 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);
关于javascript - 在 JavaScript 中第 n 次出现正则表达式时分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19736367/