我正在尝试从具有各种不同行的文件中获取输入。
例如格式为书名,作者:借款人名:借款人所在国
这里有一些示例行。
The Lord of the Rings, JRR Tolkien:McInnes Elizabeth:13 11 10
Crime And Punishment, Fyodor Dostoyevsky
The Clan Of The Cave Bear, Jean M Auel
The God Of Small Things, Arundhati Roy:Robins Joshua:20 11 10
所以我在设置扫描仪后尝试使用 useDelimiter,但由于某些行较短,我不知道该怎么做。
最佳答案
下面是一个基于正则表达式的解决方案:
import java.io.*;
import java.util.regex.*;
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
Pattern p = Pattern.compile("(.+?),(.+?)(?::(.+?):(\\d+ \\d+ \\d+))?");
String line;
while (null != (line = br.readLine())) {
Matcher m = p.matcher(line);
if (m.matches()) {
String title = m.group(1);
String author = m.group(2);
String borrower = m.group(3);
String data = m.group(4);
System.out.println("Title: " + title);
System.out.println("Author: " + author);
if (borrower != null) {
System.out.println(" Borrower: " + borrower);
System.out.println(" Data: " + data);
}
}
System.out.println();
}
br.close();
}
}
根据您的示例输入,它会打印:
Title: The Lord of the Rings
Author: JRR Tolkien
Borrower: McInnes Elizabeth
Data: 13 11 10
Title: Crime And Punishment
Author: Fyodor Dostoyevsky
Title: The Clan Of The Cave Bear
Author: Jean M Auel
Title: The God Of Small Things
Author: Arundhati Roy
Borrower: Robins Joshua
Data: 20 11 10
关于来自格式化文件的 Java 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4318153/