Java扫描程序-下一个字符串,直到|被发现 [英] Java Scanner - next String until a | is found
问题描述
目前,我正在尝试阅读以下格式的一些基本单元格:
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.
推荐答案
请参见扫描仪的Javadoc ,其中有一个示例:
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();
打印以下输出:
1
2
red
blue
那么您可以使用|
作为分隔符.
Well you can use |
as delimiter.
要将|
用作分隔符,应使用\\s*\\|\\s*
或\\s*[|]\\s*
对其进行转义.如果按原样使用|
,则将仅获得第一个值1
和异常InputMismatchException
.
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();
}
}
输出:
1
2
red
blue
这篇关于Java扫描程序-下一个字符串,直到|被发现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!