我的文本文件如下: {11-11,22},{33-33,44},... {88-88,99}
如何在Java中将其转换为2维数组: [[11-11,22],[33-33,44],... [88-88,99]]
答案 0 :(得分:2)
String source = "{11-11,22},{33-33,44},{88-88,99}";
String[] splittedSource = source.split("(?<=\\}),(?=\\{)");
Pattern p = Pattern.compile("\\{([^,]+),([^\\}]+)");
String[][] result = new String[splittedSource.length][2];
for(int i = 0; i < splittedSource.length; i++) {
Matcher m = p.matcher(splittedSource[i]);
while(m.find()) {
result[i][0] = m.group(1);
result[i][1] = m.group(2);
System.out.print(m.group(1) + " " + m.group(2) + "\n");
}
}
System.out.println(Arrays.deepToString(result));
source.split("(?<=\\}),(?=\\{)");
- 在&{39; ,
&#39;上分享来源字符前面带有&#39; }
&#39;然后是&#39; {
&#39;
Pattern.compile("\\{([^,]+),([^\\}]+)");
- 括号中的两个捕获群组&#34; ()
&#34;,首先包含&#39; ,
以外的所有字符&#39;直到它到达,
&#39;,第二个包含&#39; ,
&#39;之后的所有字符。除了&#39; }
&#39;
new String[splittedSource.length][2];
- 此示例中的[3][2]
Matcher m = p.matcher(splittedSource[i]);
- 在这里,您要说明您将针对来自splittedSource[]
您从此代码获得的输出:
11-11 22
33-33 44
88-88 99
[[11-11, 22], [33-33, 44], [88-88, 99]]
答案 1 :(得分:-1)
public static void main(String[] args) {
Scanner in = new Scanner(Thread.currentThread().getContextClassLoader().
getResourceAsStream("input/test.txt"));
String line = in.nextLine();
String[] tokens = line.split("},");
String[][] finalArray = new String[tokens.length][2];
for (int i = 0; i < tokens.length; i++) {
tokens[i] = tokens[i].replace("{", "");
tokens[i] = tokens[i].replace("}", "");
finalArray[i] = tokens[i].split(",");
}
for (int i = 0; i < finalArray.length; i++) {
System.out.println(Arrays.toString(finalArray[i]));
}
}