Scannerクラスを使用して、next(Pattern pattern)メソッドを使用して行を読み取り、コロンの前とコロンの後にテキストをキャプチャして、s1=textbeforecolonおよびs2=textaftercolonとなるようにしようとしています。
行は次のようになります。
何か:何か他
Scannerクラスを使用して、next(Pattern pattern)メソッドを使用して行を読み取り、コロンの前とコロンの後にテキストをキャプチャして、s1=textbeforecolonおよびs2=textaftercolonとなるようにしようとしています。
行は次のようになります。
何か:何か他
これを行うには、具体的に何が必要かによって、2つの方法があります。
useDelimiter()
入力全体をコロンで分割する場合は、他の人が指摘しているように、このメソッドを使用できます。
// You could also say "scanner.useDelimiter(Pattern.compile(":"))", but
// that's the exact same thing as saying "scanner.useDelimiter(":")".
scanner.useDelimiter(":");
// Examines each token one at a time
while (scanner.hasNext())
{
String token = scanner.next();
// Do something with token here...
}
各行をコロンで分割する場合は、String
のsplit()
メソッドを使用する方がはるかに簡単です。
while (scanner.hasNextLine())
{
String[] parts = scanner.nextLine().split(":");
// The parts array now contains ["something", "somethingelse"]
}
スキャナーでPatternを使用したことはありません。
私はいつも文字列でデリメータを変更しました。 http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html#useDelimiter(java.lang.String)
File file = new File("someFileWithLinesContainingYourExampleText.txt");
Scanner s = new Scanner(file);
s.useDelimiter(":");
while (!s.hasNextLine()) {
while (s.hasNext()) {
String text = s.next();
System.out.println(text);
}
s.nextLine();
}