问题
Currently I'm trying to read through some basic cells, in this format:
+-------+-------+
| | |
+-------+-------+
Now I need to get the string representation of the cell's contents and send it off to another method. The problem is that the cells have no pre-defined length. I'm reading these from a file, so my easiest option should be to just use the Scanner I already have set up. Problem is, I don't really know how for this case.
I have a strong feeling that I need to use the pattern somehow, but I'm at a complete loss on how to do it.
I could also probably just build it up somehow, but that strikes me as being painfully slow.
回答1:
See javadoc for Scanner, it has an example :
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
prints the following output:
1
2
red
blue
Well you can use |
as delimiter.
EDIT : To use |
as a delimiter you should escape it, Use \\s*\\|\\s*
or \\s*[|]\\s*
. If you use |
as it is, then you will get only 1st value 1
and exception InputMismatchException
.
See below program and output :
public class Test {
public static void main(String[] args) {
String input = "1 | 2 | red | blue |";
Scanner s = new Scanner(input).useDelimiter("\\s*\\|\\s*"); // or use "\\s*[|]\\s*"
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
}
}
Output :
1
2
red
blue
来源:https://stackoverflow.com/questions/12985365/java-scanner-next-string-until-a-is-found