gpt4 book ai didi

java - 从复杂字符串中检索整数

转载 作者:行者123 更新时间:2023-12-01 07:01:10 25 4
gpt4 key购买 nike

我有一个读取某个文件内容的代码。文件的开头如下:

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\

我想将每个整数存储在一个大小为 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] + " ");
}

我正在考虑删除“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\

有人可以帮我解决我的问题吗?谢谢!

最佳答案

您可以使用正则表达式来匹配您想要的字符,而不是替换所有您不需要的字符。

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();
}

正则表达式 J-(\d+) 匹配以“J-”开头并以一个或多个数字结尾的字符串的一部分。数字两边的括号创建一个捕获组,我们可以直接访问它,而不必替换“J-”。

如果您确定要将 ID 解析为整数,请注意解析时“073”会变成 73。不确定这对您是否有影响。另外,如果一行上可能超过 10 个 ID,请使用 ArrayList 并在其中添加 ID,而不是将它们放入固定大小的数组中。

关于java - 从复杂字符串中检索整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49716341/

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