Javaのスキャナ次の(パターン・パターン)を使用してテキストを読みます
-
20-08-2019 - |
質問
私はそのように、S1 = textbeforecolonとs2 = textaftercolonます。
コロンの前にテキストをキャプチャするために、次の(柄模様)メソッドを使用してラインを読み、コロンの後にするScannerクラスを使用しようとしていますの行は次のようになります:
何か:somethingelse
解決
あなたが望む、具体的内容によって、これを行うには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"]
}
他のヒント
私はスキャナでパターンを使用したことがありません。
私はいつも単なる文字列と区切り文字を変更しました。 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();
}
所属していません StackOverflow