Java 从字符串中删除除数组中的a-z以外的所有字符

Java 从字符串中删除除数组中的a-z以外的所有字符,java,arrays,Java,Arrays,我正在尝试从文本文件中读取单词并将其存储在数组中。我尝试的代码的问题如下所示,它读取所有字符,例如“单词”和“读取”。但我只希望数组中包含“单词”和“读取” public String[] openFile() throws IOException { int noOfWords=0; Scanner sc2 = new Scanner(new File(path)); while(sc2.hasNext()) { noOfWords++;

我正在尝试从文本文件中读取单词并将其存储在数组中。我尝试的代码的问题如下所示,它读取所有字符,例如“单词”和“读取”。但我只希望数组中包含“单词”和“读取”

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;
}
public String[]openFile()引发IOException
{
int noOfWords=0;
Scanner sc2=新扫描仪(新文件(路径));
while(sc2.hasNext())
{
noOfWords++;
sc2.next();
}
Scanner sc3=新扫描仪(新文件(路径));
字符串bagOfWords[]=新字符串[noOfWords];
对于(int i=0;i使用正则表达式替换:

replaceAll("([^a-zA-Z]+)","");
把这条线应用到

bagOfWords[i] = sc3.next().replaceAll("([^a-zA-Z]+)","");
使用正则表达式替换:

replaceAll("([^a-zA-Z]+)","");
把这条线应用到

bagOfWords[i] = sc3.next().replaceAll("([^a-zA-Z]+)","");
使用此代码:

for (int i = 0; i < noOfWords; i++) {
     bagOfWords[i] = sc3.next().replaceAll("[^A-Za-z0-9 ]", "");
}
for(int i=0;i
使用以下代码:

for (int i = 0; i < noOfWords; i++) {
     bagOfWords[i] = sc3.next().replaceAll("[^A-Za-z0-9 ]", "");
}
for(int i=0;i
您可能只需要字母。在这种情况下,您可以使用
Character.isleter(char)
方法

片段:

String token = "word1";
String newToken = "";
for (int i = 0; i < token.length(); i++) {
    char c = token.charAt(i);
    if(java.lang.Character.isLetter(c)){
        newToken += c;
    }
}
System.out.println(newToken);
String-token=“word1”;
字符串newToken=“”;
对于(int i=0;i
您可能只需要字母。在这种情况下,您可以使用
Character.isleter(char)
方法

片段:

String token = "word1";
String newToken = "";
for (int i = 0; i < token.length(); i++) {
    char c = token.charAt(i);
    if(java.lang.Character.isLetter(c)){
        newToken += c;
    }
}
System.out.println(newToken);
String-token=“word1”;
字符串newToken=“”;
对于(int i=0;i
括号和+不是必需的,您只需要[^a-zA-Z]。如果您解释正则表达式模式以及replaceAll如何使用它,可能会对OP有所帮助。是的,我知道,我认为+将替换一组字符,而不是每个字符。因此,它不会浪费每个正则表达式匹配的内存地址括号和+不是必需的,您只需要[^a-zA-Z]。如果您解释正则表达式模式以及replaceAll如何使用它,可能会对OP有所帮助。是的,我知道,我认为+将替换一组字符,而不是每个字符。因此,它不会浪费每个正则表达式匹配的内存地址