了解Scanner中的useDelimiter:为什么我得到空白令牌? [英] Understanding useDelimiter in Scanner : why I get blank token?

查看:194
本文介绍了了解Scanner中的useDelimiter:为什么我得到空白令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带分隔符的扫描仪,我遇到了一个我想要理解的奇怪行为。

I'm using scanner with delimiter and I've came across a strange behaviour I'd like to understand.

我正在使用这个程序:

    Scanner sc = new Scanner("Aller à : Navigation, rechercher");
    sc.useDelimiter("\\s+|\\s*\\p{Punct}+\\s*");
    String word="";
    while(sc.hasNext()){
        word = sc.next();
        System.out.println(word);
    }

输出为:

Aller
à

Navigation
rechercher

所以首先我不明白为什么我得到一个空白令牌,文档说:

So first I don't understand why I'm getting a blank token, the documentation says :


取决于分隔的类型模式,可以返回空标记。例如,模式\s +将不返回空标记,因为它匹配分隔符的多个实例。分隔模式\ s可以返回空标记,因为它一次只传递一个空格。

Depending upon the type of delimiting pattern, empty tokens may be returned. For example, the pattern "\s+" will return no empty tokens since it matches multiple instances of the delimiter. The delimiting pattern "\s" could return empty tokens since it only passes one space at a time.

我正在使用 \\\\ + 所以为什么它返回一个空白令牌?

I'm using \\s+ so why it returns a blank token?

然后我还想了解有关正则表达式的其他事项。如果我使用反向正则表达式更改分隔符:

Then there is an other thing I'd like to understand concerning regex. If I change the delimiter using the "reversed" regex :

    sc.useDelimiter("\\s*\\p{Punct}+\\s*|\\s+");

输出是正确的,我得到:

The output is correct and I get :

Aller
à
Navigation
rechercher

为什么它会起作用?

Why it works in the way?

编辑:

在这种情况下:

    Scanner sc = new Scanner("(23 ou 24 minutes pour les épisodes avec introduction) (approx.)1");
    sc.useDelimiter("\\s*\\p{Punct}+\\s*|\\s+"); //second regex

我在介绍。是否可以避免它?

I still have a blank token between introduction and approx. Is it possible to avoid it?

推荐答案

我感觉你在有空格的地方造成两个分隔符捕获然后是标点符号。为什么不简单地使用 [\\\\\\p {Punct}] +

I have a feeling that you are causing two delimiter captures in places where there's a blank space followed by punctuation. Why not simply use [\\s\\p{Punct}]+?

此正则表达式 \\\\ + | \\p {Punct} + 将首先捕获空空格并吞下它,然后将下一个分隔符捕获为标点符号。这将是两个彼此相邻的分隔符,两者之间没有任何内容(空令牌)。

This regex \\s+|\\p{Punct}+ will first capture the empty space and swallow it, then will capture the next delimiter as the punctuation. That will be two delimiters next to each other with nothing in between (the empty token).

这篇关于了解Scanner中的useDelimiter:为什么我得到空白令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆