String.replaceAll 方法是否有只保留字母和空格的正则表达式

Is there a regex to the String.replaceAll method that only keeps letters and white spaces

我制作了一个程序,可以计算一个单词在一个很长的字符串中出现的频率。我的问题是程序正在计算例如“*it”(考虑 * 引号)和 "it" 作为不同的词,因此将它们放在不同的类别中。

我尝试用以下代码替换我知道的所有标点符号:

text = text.replace("\n", " ");
text = text.replaceAll("\p{Punct}", " ");
text = text.replace("\"", "");
text = text.replace("–", "");
text = text.replace("\t", "");

不幸的是,代码没有用,我认为这是因为 Unicode 中有很多不同的引号,我看不出它们之间的区别,所以有没有办法删除所有 Unicode 字符,除了使用 String.replaceAll 方法的字母和空格,还是我必须制作一个 CharArray 并从那里继续?

非常感谢,如有任何帮助,我们将不胜感激。

我想这样可以

text = text.replaceAll("[^a-zA-Z0-9 ]", "");

这将删除所有非字母数字或特殊字符的字符。

编辑:-

根据@npinti

的建议
text = text.replaceAll("[^\p{L}0-9 ]", "");

这将删除所有非字母和空格。

text.replaceAll("[^\sa-zA-Z]", "");

图例:

  • ^ - 排除给定字符被替换
  • \s - 所有空格(\n、\t、' ')
  • a-zA-Z - 所有字母

示例:

String in="12ASxA  sdr5%";
System.out.println(in.replaceAll("[^\sa-zA-Z]", "")); // ASxA  sdr

这将删除所有 non-letter/digit 个字符并压缩空格,这样您就不会得到多个连续的空格:

text = text.replaceAll("[^\p{L}\d]+", " ");