2 回答

TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以嘗試使用String#matches來(lái)識(shí)別感興趣的線:
List<String> names = new ArrayList<>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.matches("^Name:.*")) {
names.add(line.replaceAll("^Name:\\s+", ""));
}
}
這里的想法是獲取所有以 開(kāi)頭的行Name:,然后刪除Name:前綴,留下您想要的內(nèi)容。
使用的正則表達(dá)式說(shuō)明:
^ from start of string (line)
Name: match text 'Name:'
\\s+ followed by any number of spaces (or other whitespace)
因此,通過(guò)刪除^Name:\\s+,我們應(yīng)該只剩下它左側(cè)的名稱(chēng)信息。
編輯:
例如,如果您的姓名內(nèi)容實(shí)際上是名字和姓氏,那么每一行將如下所示:
Name: George Washington
在這種情況下,如果格式固定,我們可以嘗試使用String#split隔離名和姓:
String[] parts = line.split("\\s+");
String first = parts[1];
String last = parts[2];
// then store first and last in separate lists
你會(huì)做什么完全取決于你的實(shí)際數(shù)據(jù)。這里有很多邊緣情況。也許有些行只有一個(gè)名字,或者有些行有中間名、首字母、后綴等。這只是為了給你一個(gè)大概的概念。

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超4個(gè)贊
以下是從提供的文件中提取名稱(chēng)列表的功能方法:
public List<String> getNames(File file) throws IOException { return Files.lines(file.toPath()) .filter(str -> str.contains("Name: ")) .map(str -> str.split("Name: ")[1]) .collect(Collectors.toList());}
添加回答
舉報(bào)