看起来你的输入在第一个数字开始到下一个开始数字之间有一个固定长度 (7):
16.1 14.3 8.8 7.0 7.85 13.29 18.75 13.08 13.10
^^^^^^^--------(7)
在这种情况下,您可以使用以下正则表达式将输入分割:(?<=\\G.{7})
。请参考此链接了解更多信息:
String text1 = "16.1 14.3 8.8 7.0 7.85 13.29 18.75 13.08 13.10";
String text2 = "6.7 5.4 6.39 ";
String[] split1 = text1.split("(?<=\\G.{7})");
String[] split2 = text2.split("(?<=\\G.{7})");
输出
[16.1 , 14.3 , 8.8 , 7.0 , 7.85 , 13.29 , 18.75 , 13.08 , 13.10]
[6.7 , 5.4 , , , 6.39 , , , , ]
如果你希望得到null而不是空值,可以使用以下代码:
List<String> result = Arrays.asList(text2.split("(?<=\\G.{7})"))
.stream()
.map(input -> input.matches("\\s*") ? null : input.trim())
.collect(toList());
输出
[16.1, 14.3, 8.8, 7.0, 7.85, 13.29, 18.75, 13.08, 13.10]
[6.7, 5.4, null, null, 6.39, null, null, null, null]
text2
末尾有空格吗? - revo(?<=\\G.{7})
吗? - Pranit MoreList<List<String>> matrix = Arrays.asList(text.split("\n"))
.stream()
.map(line -> Arrays.asList(line.split("\\s+")))
.collect(Collectors.toList())
这将给你一个二维数组/列表的值。
当进行测试时:
String text = "16.1 14.3 8.8 7.0 7.85 13.29 18.75 13.08 13.10\n" + " 6.7 5.4 6.39";
这将输出:
[[16.1, 14.3, 8.8, 7.0, 7.85, 13.29, 18.75, 13.08, 13.10], [, 6.7, 5.4, 6.39]]
Splitter.fixedLength(int)
方法String[] rows = {
"16.1 14.3 8.8 7.0 7.85 13.29 18.75 13.08 13.10",
"6.7 5.4 6.39 "
};
Splitter splitter = Splitter.fixedLength(7);
for(String row: rows) {
List<String> data = splitter.splitToList(row);
for (int i = 0; i < data.size(); i++) {
System.out.printf("Column %d: %s%n", i+1, data.get(i));
}
}
对我来说,这似乎是一个定宽文件。
请尝试以下正则表达式。
.{7}
您可以根据列宽在花括号内更改值,
.{column_width_goes_here}
"\\\s+"
is not a valid RegEx. It should be"\\s+"
- Saif AhmadTAB
间隔的。请查看@YCF_L的解决方案。那是正确的解决方案。 - Pranit More