【问题标题】:Java Scanner hasNext(String) method do not match sometimesJava Scanner hasNext(String) 方法有时不匹配
【发布时间】:2013-04-07 17:14:53
【问题描述】:

我尝试使用 Java Scanner hasNext 方法,但得到了奇怪的结果。也许我的问题很明显,但为什么这个简单的简单表达式"[a-zA-Z']+" 不适用于这样的词:“点。任何事情,主管,”。我也试过这个"[\\w']+"。

public HashMap<String, Integer> getDocumentWordStructureFromPath(File file) {
    HashMap<String, Integer> dictionary = new HashMap<>();
    try {
        Scanner lineScanner = new Scanner(file);
        while (lineScanner.hasNextLine()) {
            Scanner scanner = new Scanner(lineScanner.nextLine());
            while (scanner.hasNext("[\\w']+")) {
                String word = scanner.next().toLowerCase();
                if (word.length() > 2) {
                    int count = dictionary.containsKey(word) ? dictionary.get(word).intValue() + 1 : 1;
                    dictionary.put(word, new Integer(count));
                }
            }
            scanner.close();
        }
        //scanner.useDelimiter(DELIMITER);
        lineScanner.close();

        return dictionary;

    } catch (FileNotFoundException e) { 
        e.printStackTrace();
        return null;
    }   
}

【问题讨论】:

    标签: parsing java.util.scanner


    【解决方案1】:

    你的正则表达式应该是这样的[^a-zA-z]+,因为你需要分隔所有不是字母的东西:

    // previous code...
    Scanner scanner = new Scanner(lineScanner.nextLine()).useDelimiter("[^a-zA-z]+");
        while (scanner.hasNext()) {
            String word = scanner.next().toLowerCase();
            // ...your other code
        }
    }
    // ... after code
    

    编辑——为什么不能使用 hasNext(String) 方法??

    这一行:

    Scanner scanner = new Scanner(lineScanner.nextLine());
    

    它真正做的是为你编译一个 whitespce 模式,所以如果你有这个测试行 "Hello World. A test, ok." 它会给你这个令牌:

    • 你好
    • 世界。
    • 一个
    • 测试,
    • 好的。

    然后,如果您使用 scanner.hasNext("[a-ZA-Z]+"),您是在询问扫描仪 if there is a token that match your pattern,对于本示例,它将为第一个令牌声明 true:

    • 您好(因为这是与您指定的模式匹配的第一个标记)

    对于下一个标记(World.)it doesn't match the pattern,它只会简单地fail 和scanner.hasNext("[a-ZA-Z]+") 将返回false,因此它永远不会适用于前面任何不是字符的单词一封信。明白了吗?

    现在...希望这会有所帮助。

    【讨论】:

    • 非常感谢@Angel Rodriguez,这是一个很好的解决方案,但我不知道为什么不使用 hasext(String) 函数。
    • 好吧,我明白你的意思了,我已经编辑了帖子……我解释了为什么它不起作用……希望对你有帮助……
    • 非常感谢,我知道了。非常感谢您的帮助。 +1 详细说明。
    猜你喜欢
    • 1970-01-01
    • 2013-03-28
    • 2019-12-27
    • 2020-03-10
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 2016-07-30
    相关资源
    最近更新 更多