如何限制filescanner只导入某些字符?

时间:2018-03-07 18:10:22

标签: java string

我想从单词列表中读取单词,但只读包含字母字符的单词,所以没有像é,ï, - 等特殊字符

这是我到目前为止所得到的:

ArrayList<String> list = new ArrayList<>();
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
File file = new File(classLoader.getResource("wordlist.txt").getFile());
try (Scanner fileScanner = new Scanner(file)) {
    while (fileScanner.hasNext()) {
        String line = fileScanner.nextLine();
        if (line.length() == 5) {          
            list.add(line);
        }
    }
} catch (IOException ioe) {
    System.out.println("The file doesn't exists!");
}

2 个答案:

答案 0 :(得分:0)

您可以使用正则表达式一次性检查字符串内容及其长度:

Pattern pattern = Pattern.compile("^[a-zA-z]{1,5}$");
try (Scanner fileScanner = new Scanner(file)) {
    while (fileScanner.hasNext()) {
        String line = fileScanner.nextLine();
        if (Pattern.matcher(line).matches()) {          
            list.add(line);
        }
    }
} catch (IOException ioe) {
    System.out.println("The file doesn't exists!");
}

答案 1 :(得分:0)

只需添加第二个条件:

youredittextid.setShowSoftInputOnFocus(false);

cat namen

if (line.length() == 5 && line.matches ("[A-Z][a-z]*")) {        

列表

Müler
J. F. Kennedy
Janis Joplin
Mirii
Renée