Reading text with Java Scanner next(Pattern pattern)

旧巷老猫 提交于 2019-12-10 20:55:44

问题


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.

The line looks like this:

something:somethingelse


回答1:


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:

// 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:

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



回答2:


I've never used Pattern with scanner.

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)




回答3:


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


来源:https://stackoverflow.com/questions/842496/reading-text-with-java-scanner-nextpattern-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!