java - 如何使用正则表达式在文本文件中查找一系列数据?

标签 java regex

我有一个包含以下系列的文本文件:

Lots of textLots of textLots of textLots of textLots of textLots of textLots
 of textLots of textLots of textLots of textLots of textLots of textLots of
 textLots of textLots of textLots of textLots of textLots of textLots of
 textLots of text

Wave amplitude (mean, 3.0 & 7.0 above LES) (mmHg)
43-152
35.9
N/A
N/A
N/A
43.5
21.9
N/A
37.3
N/A
40.9
N/A

    Wave duration (mean at 3.0 & 7.0 above LES) (sec)
2.7-5.4
2.5
N/A
N/A
N/A
2.2
3.0
N/A
2.2
N/A
2.6
N/A

    Onset velocity (between 11.0 & 3.0 above LES) (cm/s)
2.8-6.3
2.2
N/A
N/A
N/A
2.5
1.0
N/A
2.5
N/A
2.7
N/A

Some other textSome other textSome other textSome other textSome other textSome
 other textSome other textSome other textSome other textSome other textSome 
other textSome other textSome other textSome other textSome other textSome 
other text

规则是:

  1. 第一行总是在某处包含括号,而在其他地方找不到。

  2. 每组数字(或一系列 N/A)末尾始终有一个空行

  3. 这些值都是数字(带或不带小数点)或 N/A。

  4. 我不想捕获每个 block 标题后的第一个数字(通常也包含 - 或 <)

我想将标题和后续数字捕获到一个数组列表中。

因此,第一个示例的预期输出为

[Wave amplitude (mean, 3.0 & 7.0 above LES  (mmHg),35.9,N/A,N/A,N/A,43.5,21.9,N/A,37.3,N/A,40.9,N/A]

我被困在可以让我实现这一目标的正则表达式上。因为我想要提取的文本位于更大的文本文件中,所以我认为我需要使用正则表达式来提取我感兴趣的部分。我想另一种选择是只选择整个部分的开头和结尾我感兴趣,但它仍然依赖于一些正则表达式,我认为执行此操作的模式会更复杂。

最佳答案

如果你真的想使用正则表达式来解析它,你可以这样做:

String pattern = "(?<desc>.*\\(.*\\).*)\n.*-.*\n(?<data>(?:N/A\n|\\d*\\.\\d*\n)+)";

String rawData = new String(Files.readAllBytes(Paths.get("indata.txt")));
Matcher seriesMatcher = Pattern.compile(pattern).matcher(rawData);
while(seriesMatcher.find()) {
    List<String> series = new ArrayList<>();
    series.add(seriesMatcher.group("desc").trim());
    series.addAll(asList(seriesMatcher.group("data").split("\n")));
    System.out.println(series);
}

正则表达式由几个部分组成:

(?<desc>.*\\(.*\\).*)\n.*-.*\n(?<data>(?:N/A\n|\\d*\\.\\d*\n)+)
--------------------- ------- ---------------------------------
description           ignore  data

描述 = 包含一对匹配括号的行。
ignore = 带有短划线的行,将被忽略。
data = 条目,即任意行数,N/A 或十进制数。

关于java - 如何使用正则表达式在文本文件中查找一系列数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37805692/

相关文章:

java - Spring:如何替换在Application Context中创建的Environment bean

java - Spring Integration 使用 activeMQ 发送但未接收消息

java - Dagger 2 : Multiple entries with same key

php - 匹配括号内的所有子字符串,但以黑名单单词开头的子字符串

javascript - 从 var 值中查找特定模式

php - 获取字符串中以 @ 开头的所有片段

java - jMagick - 图像比较

java - 在继承和利用不同类中的属性方面遇到麻烦

Javascript 正则表达式 - 从字符串中获取函数名称

sql - 将查询与 SQL 中的正则表达式匹配?