【发布时间】:2017-12-01 04:34:17
【问题描述】:
我正在编写一个程序,用户在其中输入一个单词 12 个字符或更少的搜索模式。单词可以由任何字母数字组合组成。我正在从用户通过命令行参数输入的文本文件中读取数据。我能够找到这个词,但也能找到不需要的嵌入词。例如,如果我正在搜索“is”并且我的文本文件包含“This”,它会告诉我它找到了不是所需结果的单词。
我在单词之前和之后放置了“”,但是如果它是一行中的第一个单词,那么它就不会找到该单词。此外,字母数字旁边的所有字符都是分隔符。因此,如果文本文件包含“this-dog”并且我的搜索模式是“this”,我希望它返回“this”作为匹配项。它应该将 - 视为一个空格。这是我目前针对我的程序这方面的代码:
try {
Scanner input = new Scanner(System.in);
boolean again = true;
boolean notTheFirst = false;
while (again) {
System.out.printf("%n%s", "Please enter a search pattern: ", "%n");
String wordToSearch = input.next();
if (wordToSearch.equals("EINPUT")) {
System.out.printf("%s", "Bye!");
System.exit(0);
}
String data;
int lineCount = 1;
try (FileInputStream fis = new FileInputStream(this.inputPath.getPath())) {
File file1 = this.inputPath;
byte[] buffer2 = new byte[fis.available()];
fis.read(buffer2);
data = new String(buffer2);
Scanner in = new Scanner(data);
while (in.hasNextLine()) {
String line = in.nextLine();
Pattern pattern = Pattern.compile(wordToSearch);
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
System.out.println("Line number " + lineCount);
String stringToFile = f.findWords(line, wordToSearch);
System.out.println();
}
lineCount++;
}
}
}
} catch (IOException e) {
throw new Exception(e.getMessage());
}
【问题讨论】:
标签: java pattern-matching