javascript - 使用正则表达式查找文本文件中段落的开头和结尾

标签 javascript regex

我有如下所示的文本文件:

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,})

Demo 2

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/

相关文章:

javascript - 如何在 JavaScript 的正则表达式中获取捕获组的索引?

regex - sed 从字符串中提取版本号(只有版本,没有其他数字)

javascript - 纯javascript中的jquery position()

javascript - 隐藏表单并显示 div

php - jQuery/AJAX 登录表单在输入时提交

java - Gradle/Java 替换文本

javascript - 如何在表单提交时阻止坏词

regex - Powershell : using -split "\s+" as opposed to . 拆分 "\s+"

Javascript 格式化数字 API

javascript - 如何让我的用户输入成为我网页上的标题?