接下来使用Java Scanner读取文本(模式模式) [英] Reading text with Java Scanner next(Pattern pattern)
问题描述
我试图使用Scanner类使用next(Pattern pattern)方法读取一行以捕获冒号之前和冒号之后的文本,以便s1 = textbeforecolon和s2 = textaftercolon.
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.
该行如下所示:
something:somethingelse
something:somethingelse
推荐答案
有两种方法,具体取决于您想要的东西.
There are two ways of doing this, depending on specifically what you want.
如果要用冒号分隔整个输入,则可以使用useDelimiter()
方法,就像其他人指出的那样:
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...
}
如果要用冒号分隔每行,那么使用String
的split()
方法会容易得多:
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"]
}
这篇关于接下来使用Java Scanner读取文本(模式模式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!