javascript - 匹配以特定单词开头和结尾的所有摘录

标签 javascript regex pattern-matching match

我有一个如下所示的文本:

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/

相关文章:

javascript - 突出显示 Angular * ngFor中的选定元素

javascript - jslint 预计!相反看到了?

python - 匹配冒号前后的短语

scala - scala中模式匹配的时间复杂度是多少?

javascript - SVG 和 JavaScript : moving elements with mouse only moves elements down and to the right

javascript - 如何使用 pdf.js 呈现 pdf 文件?

php - substr 计数返回错误结果

惰性分组后的正则表达式匹配字符

ios - Swift 2.2 中的自定义模式匹配未按预期工作

opencv - 两个截然不同的图像之间的模式识别