【问题标题】:Split a string at nth occurrence of a regex in javascript在javascript中第n次出现正则表达式时拆分字符串
【发布时间】:2013-11-01 22:23:00
【问题描述】:

我知道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 的解决方案以在第 nth 个正则表达式出现时拆分字符串的任何想法?

【问题讨论】:

    标签: javascript regex arrays string split


    【解决方案1】:
    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

    【讨论】:

    • 谢谢。这比我的解决方案要好,但我正在寻找一种解决方案,通过第 n 次出现正则表达式来拆分字符串。您的解决方案仅按第一次出现来拆分字符串。
    • 阿米尔,请举例说明源文本和第 N 次出现(N=2 或更多)的结果。
    • 想象一下这个字符串:'this-----that---these-----those'。如果 N=2(从 1 开始),结果应该是:['this-----that', 'these-----those']
    • 太棒了! :) 是否可以使用任何正则表达式来做到这一点?假设我们要编写一个函数,获取字符串、正则表达式和 N,然后返回结果数组!
    • 拥有一个函数,我的意思是一个函数,它自己生成所需的正则表达式,并让使用该函数的人的行为透明。 split('this-----that---these------those', /---*/, 2) 例如。所以我们可以通过这种方式将它与任何正则表达式一起使用!无论如何,谢谢您的回复!真的很感激:)
    猜你喜欢
    • 2019-04-02
    • 2018-10-16
    • 2011-06-18
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    • 2016-09-15
    • 1970-01-01
    相关资源
    最近更新 更多