1
正则表达式的第n次出现的字符串,我知道split
可以得到第二个参数的限制,但它不是我要找的。我知道这可以通过分割并再次连接一个固定的字符串分隔符来完成。拆分在JavaScript的
的问题是分隔符是一个正则表达式,我不知道,匹配模式的精确长度。
考虑这个字符串:
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次出现分裂的字符串。您的解决方案仅在第一次出现时拆分字符串。 –
埃米尔,举例说明源文本和第N次出现(N = 2或更多)情况下的结果。 – ReinRaus
想象一下这个字符串:'this ----- that --- these ------ those'。如果N = 2(1型)时,结果应该是:[“这个-----即”,“这些------那些”] –