简体   繁体   English

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

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

I know split can get a second parameter as a limit, but it is not what I'm looking for.我知道split可以获得第二个参数作为限制,但这不是我想要的。 And I know it can be done by splitting and joining again with a solid string delimiter.而且我知道它可以通过使用实心字符串分隔符拆分和再次连接来完成。

The problem is the delimiter is a regular expression and I don't know the exact length of the pattern that matches.问题是分隔符是一个正则表达式,我不知道匹配模式的确切长度。

Consider this string:考虑这个字符串:

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

By using this:通过使用这个:

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

I will get:我会得到:

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

And this is what I wanted to be: (if I want to split by the first occurrence )这就是我想要的:(如果我想在第一次出现时拆分)

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

This solution is what I currently have, but it's just for the first occurrence.这个解决方案是我目前所拥有的,但这只是第一次出现。

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

Any ideas on how to generalize the solution for any number n to split the string on the n th occurrence of regex?关于如何推广任何数字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);

Output:输出:

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

jsFiddle js小提琴
Option with the function:功能选项:

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 js小提琴

Option with the function 2:具有功能 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 js小提琴

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

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