useDelimiter()打印空白处

huangapple go评论73阅读模式
英文:

useDelimiter() printing empty space

问题

我有一个字符串,```String url = "www.public.website.edu/~JohnSmith/JAVA000";```。我打算使用分隔符来获取如下所示的期望输出。

我有点儿明白输出了,但似乎多了一行我不确定它从哪里来的。

代码:
public static void main(String[] args) {
    String url = "www.public.website.edu/~JohnSmith/JAVA000";
    Scanner scan = new Scanner(url);
    scan.useDelimiter("[./~]");
    while (scan.hasNext()) {
        System.out.println(scan.next());
    }

实际输出:

www
public
website
edu

JohnSmith
JAVA000


期望输出:

www
public
website
edu
JohnSmith
JAVA000


我不太确定我的正则表达式语法出了什么问题。
英文:

I have a string, String url = "www.public.website.edu/~JohnSmith/JAVA000";. I aim to use delimiters to get the desired output as shown below.

I do kinda get the ouput, but there seems to be an extra line that's printed and I'm not entirely sure where it comes from.

Code:

	public static void main(String[] args) {
		String url = "www.public.website.edu/~JohnSmith/JAVA000";
		Scanner scan = new Scanner(url);
		scan.useDelimiter("[./~]");
		while (scan.hasNext()) {
			System.out.println(scan.next());
		}

Actual:

www
public
website
edu

JohnSmith
JAVA000

Expected:

www
public
website
edu

JohnSmith
JAVA000

I'm not entirely sure where my regex syntax is going wrong.

答案1

得分: 2

next会持续读取您提供给扫描器的字符串,直到找到分隔符为止,并返回所读取的字符串。

让我们看看在扫描器读取了edu之后会发生什么。扫描器的位置现在位于:

www.public.website.edu/~JohnSmith/JAVA000
                      ^

它开始通过转到下一个字符来进行阅读。它注意到下一个字符~也是一个分隔符,因为它与正则表达式[./~]匹配,所以它在这里停止。扫描器读取了哪个非分隔符字符?没有!因此,next返回一个空字符串,您打印了该空字符串,从而导致出现空行。

如果您不喜欢空行,您可以指定分隔符是[./~]中的一个或多个字符,使用+量词:

scan.useDelimiter("[./~]+");

这样,/~将被视为一个分隔符,而不是两个单独的分隔符。

英文:

next will keep reading the string you gave the scanner, until a delimiter is found, and return the string that is read.

Let's see what happens just after the scanner has read edu. The scanner's position is now at:

www.public.website.edu/~JohnSmith/JAVA000
                      ^

It starts reading by going to the next character. It sees that the next character ~ is also a delimiter, as it matches the [./~] regex, so it stops here. What non-delimiter character has the scanner read? None! So next returns an empty string, and you print that empty string, which causes the empty line to appear.

If you don't like the empty line, you can specify that a delimiter is one or more of the characters in [./~] by using the + quantifier:

scan.useDelimiter("[./~]+");

This way, /~ is treated as one delimiter, rather than 2 separate ones.

huangapple
  • 本文由 发表于 2020年9月24日 09:21:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/64038277.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定