Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading text with Java Scanner next(Pattern pattern)

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

like image 551
burntsugar Avatar asked Aug 03 '26 11:08

burntsugar


1 Answers

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"]
}
like image 87
hbw Avatar answered Aug 06 '26 08:08

hbw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!