删除标点符号,保留字母和空格 - Java Regex

all*_*uck 1 java regex string replaceall

今晚我试图从文件中解析单词,我想删除所有标点符号,同时保留大小写单词以及空格。

String alpha = word.replaceAll("[^a-zA-Z]", "");
Run Code Online (Sandbox Code Playgroud)

这将替换所有内容,包括空格。

对包含 的文本文件进行操作Testing, testing, 1, one, 2, two, 3, three.,输出变为TESTINGTESTINGONETWOTHREE 但是,当我将其更改为

String alpha = word.replaceAll("[^a-zA-Z\\s]", "");
Run Code Online (Sandbox Code Playgroud)

输出不会改变。

这是完整的代码片段:

public class UpperCaseScanner {

    public static void main(String[] args) throws FileNotFoundException {

        //First, define the filepath the program will look for. 
        String filename = "file.txt";   //Filename
        String targetFile = "";         
        String workingDir = System.getProperty("user.dir");

        targetFile = workingDir + File.separator + filename;   //Full filepath.

        //System.out.println(targetFile); //Debug code, prints the filepath. 

        Scanner fileScan = new Scanner(new File(targetFile)); 

        while(fileScan.hasNext()){
            String word = fileScan.next();
            //Replace non-alphabet characters with empty char. 
            String alpha = word.replaceAll("[^a-zA-Z\\s]", "");
            System.out.print(alpha.toUpperCase());
        }

        fileScan.close();

    }
}
Run Code Online (Sandbox Code Playgroud)

file.txt 有一行,读取Testing, testing, 1, one, 2, two, 3, three. 我的目标是让输出读取Testing Testing One Two Three 我只是在正则表达式中做错了什么,还是我需要做其他事情?如果相关,我正在使用 32 位 Eclipse 2.0.2.2。

小智 5

System.out.println(str.replaceAll("\\p{P}", ""));         //Removes Special characters only
System.out.println(str.replaceAll("[^a-zA-Z]", ""));      //Removes space, Special Characters and digits
System.out.println(str.replaceAll("[^a-zA-Z\\s]", ""));   //Removes Special Characters and Digits
System.out.println(str.replaceAll("\\s+", ""));           //Remove spaces only
System.out.println(str.replaceAll("\\p{Punct}", ""));     //Removes Special characters only
System.out.println(str.replaceAll("\\W", ""));            //Removes space, Special Characters but not digits
System.out.println(str.replaceAll("\\p{Punct}+", ""));    //Removes Special characters only
System.out.println(str.replaceAll("\\p{Punct}|\\d", "")); //Removes Special Characters and Digits
Run Code Online (Sandbox Code Playgroud)