接下来使用 Java Scanner 读取文本(模式模式)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/842496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:05:44  来源:igfitidea点击:

Reading text with Java Scanner next(Pattern pattern)

javajava.util.scannernext

提问by burntsugar

I am trying to use the Scanner class to read a line using the next(Pattern pattern) method to capture the text before the colon and then after the colon so that s1 = textbeforecolon and s2 = textaftercolon.

我正在尝试使用 Scanner 类读取一行,使用 next(Pattern pattern) 方法来捕获冒号之前和冒号之后的文本,以便 s1 = textbeforecolon 和 s2 = textaftercolon。

The line looks like this:

该行如下所示:

something:somethingelse

东西:别的东西

采纳答案by hbw

There are two ways of doing this, depending on specifically what you want.

有两种方法可以做到这一点,具体取决于您想要什么。

If you want to split the entire input by colons, then you can use the useDelimiter()method, like others have pointed out:

如果你想用冒号分割整个输入,那么你可以使用该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...
}

If you want to split each line by a colon, then it would be much easier to use String's split()method:

如果你想用冒号分割每一行,那么使用String'ssplit()方法会容易得多:

while (scanner.hasNextLine())
{
    String[] parts = scanner.nextLine().split(":");
    // The parts array now contains ["something", "somethingelse"]
}

回答by Aaron

I've never used Pattern with scanner.

我从未在扫描仪上使用过 Pattern。

I've always just changed the delimeter with a string. http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html#useDelimiter(java.lang.String)

我总是用字符串更改分隔符。 http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html#useDelimiter(java.lang.String)

回答by Alex Beardsley

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();
}