gpt4 book ai didi

java - 正则表达式不适用于 Stream filter()

转载 作者:搜寻专家 更新时间:2023-10-31 08:25:50 24 4
gpt4 key购买 nike

我试图从我在 Java 8 中使用新的 Stream 时得到的一行中获取某些文本。

这是我正在阅读的内容:

46 [core1]
56 [core1]
45 [core1]
45 [core2]
67 [core2]
54 [core2]

这是我目前阅读的代码:

Path path = Paths.get("./src/main/resources/", "data.txt");
try(Stream<String> lines = Files.lines(path)){
List<Integer> temps = new ArrayList<>();
lines
.filter(line -> line.contains("[core1]"))
.filter(line -> line.contains("(\\d+).*"))
.flatMapToInt(temperature -> IntStream.of(Integer.parseInt(temperature)))
.forEach(System.out::println);
System.out.print(temps.size());
}

我检查了 https://www.regex101.com/ 中的正则表达式它似乎工作正常。另外,如果我只搜索 [core1] 字符串,它会找到它。

问题是,当同时使用所有这些时,我得到 0 个匹配项。我目前背后的逻辑是,我读了一行,看看它是什么核心,然后在它之前得到它的编号。之后我想将它添加到列表中。

我在这里做错了什么?

最佳答案

contains 仅适用于字符串(不支持正则表达式)...您可以使用 line.matches("(\\d+).*") 来实现一样。

关于java - 正则表达式不适用于 Stream filter(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29806558/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com