Java:在文本文件中搜索特定单词
我现在有一个很大的文本文件,里面有很多最流行的名字。我让用户输入一个特定的名称,而我目前正试图打印具有该名称的行。我的问题是,如果用户输入一个像Alex这样的名字,每个包含Alex的名字,比如Alexander,Alexis,Alexia,都会被打印出来,而我只希望Alex被打印出来。我能对ifline.ContainesName做些什么来解决这个问题。 该行包含的信息包括姓名、人气排名以及使用该姓名的人数Java:在文本文件中搜索特定单词,java,Java,我现在有一个很大的文本文件,里面有很多最流行的名字。我让用户输入一个特定的名称,而我目前正试图打印具有该名称的行。我的问题是,如果用户输入一个像Alex这样的名字,每个包含Alex的名字,比如Alexander,Alexis,Alexia,都会被打印出来,而我只希望Alex被打印出来。我能对ifline.ContainesName做些什么来解决这个问题。 该行包含的信息包括姓名、人气排名以及使用该姓名的人数 try { line = reader.readLine
try {
line = reader.readLine();
while (line != null) {
if(line.contains(name)){
text += line;
line = reader.readLine();
}
line = reader.readLine();
}
}catch(Exception e){
System.out.println("Error");
}
System.out.println(text);
line.equalsname
替换
line.containsnameline.equalsname
替换
line.containsname您可以将带有的正则表达式用于此任务:
final String regex = String.format("\\b%s\\b", name);
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(line);
matcher.find();
if( matcher.group(0).length() > 0 ) {
text += line;
line = reader.readLine();
}
您可以将正则表达式与用于此任务的
final String regex = String.format("\\b%s\\b", name);
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(line);
matcher.find();
if( matcher.group(0).length() > 0 ) {
text += line;
line = reader.readLine();
}
简而言之,可以使用Java8流:下面是一个例子:
public class Test2 {
public static void main(String[] args) {
String fileName = "c://lines.txt";
String name = "nametosearch";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.filter(line -> line.contains(" " + name + " ")).forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
简而言之,可以使用Java8流:下面是一个例子:
public class Test2 {
public static void main(String[] args) {
String fileName = "c://lines.txt";
String name = "nametosearch";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.filter(line -> line.contains(" " + name + " ")).forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
抱歉,忘了提及行中的其他信息,如姓名的人气排名和使用该姓名的人数..equals不起作用,请使用@Aniket Sahrawat的答案,或者您可以将行拆分为字符串数组,并使用第一个元素与输入进行比较。抱歉,忘了提及其他元素r行中的信息,如姓名的人气排名和该姓名的人数..equals wouldnt workk,请使用@Aniket Sahrawat的答案,或者您可以将该行拆分为字符串数组,并使用第一个元素与输入进行比较。