tags:

views:

2345

answers:

3

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

A: 

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)

Aaron
A: 
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();
}
Alex Beardsley
+5  A: 

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"]
}
htw
You're right, split() would probably be the best choice.
Aaron