gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:14:00 26 4
gpt4 key购买 nike

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

String alpha = word.replaceAll("[^a-zA-Z]", "");

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

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

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

输出不变。

完整的代码片段如下:

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();

}
}

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

最佳答案

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

关于java - 删除标点符号,保留字母和空格 - Java Regex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23332146/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com