我有一个代码,可以读取某个文件的内容.该文件的开头如下:
J-549 J-628 J-379 J-073 J-980 vs J-548 J-034 J-127 J-625 J-667\
J-152 J-681 J-922 J-079 J-103 vs J-409 J-552 J-253 J-286 J-711\
J-934 J-367 J-549 J-169 J-569 vs J-407 J-429 J-445 J-935 J-578\
Run Code Online (Sandbox Code Playgroud)
我想将每个整数存储在一个大小为270(行数)x 10(每行的整数)的数组中.
我没有使用正确的正则表达式.这是我的一段代码:
String strLine;
int[] id = new int[10];//list ID of each line
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
strLine = strLine.replaceAll("J-", "");
strLine = strLine.replaceAll(" vs ", " ");
String[] teamString = strLine.split(" ");
for(int i=0;i<id.length;i++) {
System.out.print(id[i] + " ");
}
Run Code Online (Sandbox Code Playgroud)
我想删除"J-"和"vs",但这似乎是一个坏主意.控制台打印:
549 628 379 073 980 548 034 127 625 667\
152 681 922 079 103 409 552 253 286 711\
934 367 549 169 569 407 429 445 935 578\
Run Code Online (Sandbox Code Playgroud)
有人可以帮助我解决我的问题.谢谢!
您可以使用正则表达式来匹配您想要的那些字符,而不是替换您不想要的所有字符.
Pattern idPattern = Pattern.compile("J-(\\d+)");
String strLine;
int[] id = new int[10]; // list ID of each line
// read file line by line
while ((strLine = br.readLine()) != null) {
Matcher lineMatcher = idPattern.matcher(strLine);
// find and parse every ID on this line
for (int i = 0; matcher.find() && i < id.length; i++) {
String idStr = matcher.group(1); // Gets the capture group 1 "(\\d+)" - group 0 is the entire match "J-(\\d+)"
int id = Integer.parseInt(idStr, 10);
id[i] = id;
System.out.print(id + " ");
}
System.out.println();
}
Run Code Online (Sandbox Code Playgroud)
正则表达式J-(\d+)匹配字符串的一部分,以"J-"开头并以一个或多个数字结尾.数字周围的括号创建了一个捕获组,我们可以直接访问它而不必替换"J-".
如果您确定要将ID解析为整数,请注意,在解析时,"073"变为73.不确定这是否会对您产生影响.此外,如果一行中可能有超过10个ID,请使用ArrayList并在其中添加ID,而不是将它们放在固定大小的数组中.
| 归档时间: |
|
| 查看次数: |
62 次 |
| 最近记录: |