我正在尝试从文本文件中读取单词并将其存储在数组中。我试过的代码中的问题如下所示,它读取所有字符,如“words”和“读。”但我只想在数组中使用“单词”和“阅读”。从字符串中移除除az之外的所有字符
public String[] openFile() throws IOException
{
int noOfWords=0;
Scanner sc2 = new Scanner(new File(path));
while(sc2.hasNext())
{
noOfWords++;
sc2.next();
}
Scanner sc3 = new Scanner(new File(path));
String bagOfWords[] = new String[noOfWords];
for(int i = 0;i<noOfWords;i++)
{
bagOfWords[i] =sc3.next();
}
sc3.close();
sc2.close();
return bagOfWords;
}
括号和+是没有必要的,你只需要[^ A-ZA-Z]。如果您解释了正则表达式模式以及replaceAll如何使用它,它可能会有利于OP。 – Shar1er80
是的,我知道,我认为+会代替一组字符而不是每个字符。所以它不会浪费每个正则表达式匹配的内存地址 –