繁体   English   中英

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

[英]Split a string at nth occurrence of a regex in javascript

我知道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"]

js小提琴
功能选项:

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);

js小提琴

具有功能 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);

js小提琴

暂无
暂无

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

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