gpt4 book ai didi

Java8 : Looking for a better way of parsing a text of "key: value" lines

转载 作者:搜寻专家 更新时间:2023-11-01 01:49:41 25 4
gpt4 key购买 nike

我有一串文本行。
有些行的格式为“键:值”。其他的可以忽略。
我有一个固定的(预定义的)键列表,我需要为其提取值并将其放入 HashMap。
所以,我正在做这样的事情:

BufferedReader reader = new BufferedReader(new StringReader(memoText));

reader.lines().forEach(line->{
if(line.startsWith("prefix1")){
// Some code is required here to get the value1
}
else if(line.startsWith("prefix2")){
// Some code is required here to get the value2
}
...
}

有没有更好的方法在 Java 8 中实现解析?

最佳答案

根据您当前的问题陈述。您可以尝试下面的代码......

  • 读取文件并从中创建流
  • 使用正则表达式编译每个字符串
  • 过滤掉所有与模式不匹配的字符串
  • 读取匹配组以映射

您可能希望根据需要更改它:

import static java.util.stream.Collectors.toMap;
//skipped
Pattern pattern = Pattern.compile("([a-zA-Z]+)\\s*:\\s*(.*)");
try (Stream<String> stream = Files.lines(Paths.get("<PATH_TO_FILE>"))) {
Map<String, String> results =
stream.map(pattern::matcher)
.filter(Matcher::find)
.collect(toMap(a -> a.group(1), a -> a.group(2)));
}

如果这不是您要找的,请告诉我

关于Java8 : Looking for a better way of parsing a text of "key: value" lines,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44192131/

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