我有一个如下所示的文本:
some non interesting part
trans-top
body of first excerpt
trans-bottom
next non interesting part
trans-top
body of second excerpt
trans-bottom
non interesting part
我想将从 trans-top 开始到 trans-bottom 结束的所有摘录提取到一个数组中。我试过了:
match(/(?=trans-top)(.|\s)*/g)
查找以 trans-top 开头的字符串。它有效。现在我想指定结束:
match(/(?=trans-top)(.|\s)*(?=trans-bottom)/g)
但事实并非如此。 Firebug 给我一个错误:
regular expression too complex
我尝试了很多其他方法,但找不到有效的解决方案...我确信我犯了一些愚蠢的错误:(。
最佳答案
这工作得很好,但它并不是全部在一个正则表达式中:
var test = "some non interesting part\ntrans-top\nbody of first excerpt\ntrans-bottom\nnext non interesting part\ntrans-top\nbody of second excerpt\ntrans-bottom\nnon interesting part";
var matches = test.match(/(trans-top)([\s\S]*?)(trans-bottom)/gm);
for(var i=0; i<matches.length; i++) {
matches[i] = matches[i].replace(/^trans-top|trans-bottom$/gm, '');
}
console.log(matches);
如果您不需要前导和尾随换行符,请将内部循环更改为:
matches[i] = matches[i].replace(/^trans-top[\s\S]|[\s\S]trans-bottom$/gm, '');
这应该会消除换行符。
关于javascript - 匹配以特定单词开头和结尾的所有摘录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6933461/