我试图使用Scanner类来读取使用下一个(模式图案)方法冒号之前,然后冒号后捕获的文本行,以便S1 = textbeforecolon和s2 = textaftercolon。

行看起来像这样:

东西:somethingelse

有帮助吗?

解决方案

有这样做,这取决于你想要什么具体的方法有两种。

如果要拆分用冒号整个输入,则可以使用该方法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...
}

如果要拆分一个冒号每一行,那么这将是更容易使用Stringsplit()方法:

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();
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top