gpt4 book ai didi

java - 用于分割文件中累积的项目数组的正则表达式行

转载 作者:行者123 更新时间:2023-12-02 09:02:06 26 4
gpt4 key购买 nike

这是我的文件中的项目列表

Name1
2019 8293
Name1
2019 8293
Name1
2019 8293
Name1
2019 8293

我想解析它并将数据添加到数据对象中。我想要的字段是字符串名称、整数年份整数人口

但假设我想先将其放入数组中。我积累了字符串,然后我想像这样分割它 String[] array = output.split(regex); 然后我想要的输出是让数组具有值 [ name1, 2019, 8293, ...]

就代码而言,我有一个关于如何处理它的计划,但这种文件格式真的让我很困惑。任何帮助将不胜感激。

注意:我尝试了 "\r\n|\n|[ ]"

最佳答案

查看您的示例所需的输出,特别是:

“然后我想要的输出是数组的值 [name1, 2019, 8293 , ...]

你可以这样做:

String[] array = {}; // Array to hold the final readin in results
List<String> list = new ArrayList<>(); // List inteferface for processing file data.
try {
// Using for/each and java.nio.file to process file contents.
for (String line : Files.readAllLines(Paths.get("Data_File.txt"), StandardCharsets.UTF_8)) {
line = line.trim(); // Trim the line of leading or trailing whitespaces.
// Skip Blank Lines (if any) in file...
if (line.equals("")) {
continue;
}
// If a file line consists of two numerical values consisting
// of one or more digits separated by one or more whitespaces...
if (line.matches("\\d+\\s+\\d+")) {
// Split the line into Year and Population then
// add them to the list.
list.add(line.split("\\s+")[0]); // Year
list.add(line.split("\\s+")[1]); // Population
}
// Otherwise the line must be a Name.
else {
// Add Name to the list.
list.add(line); // Name
}
}
// Convert List to String[] Array
array = list.toArray(new String[0]);
}
catch (IOException ex) {
System.err.println(ex);
}

// Display the results read in from file now contained within the array[] Array.
String arrayString = Arrays.toString(array);
// Remove Square Brackets ([]) for display.
System.out.println(arrayString.substring(1, arrayString.length() - 1));

上面的代码注释得很好,应该足够详细地解释正在做什么。如果您需要更多帮助,请随时询问。

Data_File.txt Contents:

Name1
2019 9999
Name2
2019 8585
Name3
2019 8888
Name4
2018 7777

Console output after running the above code:

Name1, 2019, 9999, Name2, 2019, 8585, Name3, 2019, 8888, Name4, 2018, 7777

关于java - 用于分割文件中累积的项目数组的正则表达式行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60085603/

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