我正在尝试使用Scanner类使用下一个(模式模式)方法读取一行,以便在冒号之前捕获文本,然后在冒号之后捕获,以便s1 = textbeforecolon和s2 = textaftercolon。
这条线看起来像这样:
东西:somethingelse
答案 0 :(得分:10)
有两种方法可以做到这一点,具体取决于你想要的是什么。
如果你想用冒号分割整个输入,那么你可以像其他人指出的那样使用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
的{{1}}方法会更容易:
split()
答案 1 :(得分:0)
我从未使用过模式扫描仪。
我一直只是用字符串更改了分隔符。 http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html#useDelimiter(java.lang.String)
答案 2 :(得分:0)
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();
}