我有如下所示的文本文件:
Current File: week-28\gcweb.txt (=>) ########## Old File: week-27\gcweb.txt (<=)
2019-07-21 13:20:42 ip-172-17-3-71=>
2019-07-17 13:27:12 ip-172-17-3-71<=
--------------------------------------------------
--------------------------------------------------
Current File: week-28\gcckup.txt (=>) ########## Old File: week-27\gcckup.txt (<=)
2019-07-21 13:20:46 ip-172-17-2-101=>
2019-07-17 13:27:14 ip-172-17-2-101<=
--------------------------------------------------
--------------------------------------------------
来自 Current File
的文本至 ------
表示一段或一部分。我需要分别获取所有这些,然后对其应用一些其他操作。我尝试使用正则表达式获取从 Current File
开始的整个文本.
我使用的正则表达式是:
\bCurrent File\b.+
我的问题是:如何选择一个段落的整个文本?我对正则表达式没有什么经验,希望得到这样的东西:
Current File: week28\gcweb.txt Old File: week-27\gcweb.txt
2019-07-21 13:20:42 ip-172-17-3-71 2019-07-17 13:27:12 ip-172-17-3-71
同时 (=>)
和 (<=)
只是当前和旧的指标。所以我尝试使用它来获取文件路径 \bCurrent File\b.+(=>)
但这给出了 (=>)
作为团体。
我需要提取字符串的帮助,以便我可以在此之后对它们应用其余操作。
最佳答案
我想你可以设计一些看起来像这样的表达式,
Current File:[\s\S]*?(?=--)
表达式在 regex101.com 的右上面板中进行了解释, 如果你想探索/简化/修改它,在this link ,如果愿意,您可以观察它如何与一些样本输入相匹配。
编辑:
要获取.txt
路径,我们可能会使用类似于以下的表达式:
Current File:\s*(\S+\.txt).*Old File:\s*(\S+\.txt)[\s\S]*?(?=-{4,})
const regex = /Current File:\s*(\S+\.txt).*Old File:\s*(\S+\.txt)[\s\S]*?(?=-{4,})/gm;
const str = `Current File: week-28\\gcweb.txt (=>) ########## Old File: week-27\\gcweb.txt (<=)
2019-07-21 13:20:42 ip-172-17-3-71=>
2019-07-17 13:27:12 ip-172-17-3-71<=
--------------------------------------------------
--------------------------------------------------
Current File: week-28\\gcckup.txt (=>) ########## Old File: week-27\\gcckup.txt (<=)
2019-07-21 13:20:46 ip-172-17-2-101=>
2019-07-17 13:27:14 ip-172-17-2-101<=
--------------------------------------------------
--------------------------------------------------`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
关于javascript - 使用正则表达式查找文本文件中段落的开头和结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57320391/