0
私は12文字以下の単語を1つの検索パターンとして入力するプログラムを書いています。単語は任意の英数字の組み合わせで構成できます。私は、ユーザーがコマンドライン引数で入力したテキストファイルからデータを読み込んでいます。私はその言葉を見つけることができるだけでなく、望ましくない埋め込み語を見つけることができます。たとえば、私が "is"を検索していて、テキストファイルに "This"が含まれていると、それが希望の結果ではないときに単語が見つかったと伝えられます。Regexを使ってテキストファイルから検索パターンを探す
単語の前後に配置しましたが、行の最初の単語であればその単語を見つけることができません。また、英数字の横にある文字はすべて区切り文字です。したがって、テキストファイルに "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());
}
こんにちはありがとうございました。私は同じことをしたいが、文字列でしたいのですが?これはできますか?文字列fileText = "\\ b" + str + "\\ b"; //ファイルからのテキスト 文字列searchWord = "\\ b" +検索+ "\\ b"; //検索対象の単語 – Austin
@austin thatしかし、別の質問のように聞こえる...「文字列」はどういう意味ですか?いくつか例を挙げることができますか? – Bohemian
私は別の質問で尋ねることができますが、私の質問を例で編集しました。 – Austin