删除java中的空格和特殊字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22936009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 19:22:33  来源:igfitidea点击:

Remove white space and special characters in java

javaregexstring

提问by Devendra

I have String which contains some special characters and white spaces as well.I want to remove white spaces and special character I am doing it as

我有包含一些特殊字符和空格的字符串。我想删除空格和特殊字符我正在这样做

String str =  "45,%$^ Sharma%$&^,is,46&* a$# java# Developer$#$^ in#$^ CST&^* web*&(,but He%^&^% want to move@!$@# in another team";
    System.out.println( str.replaceAll("[^a-zA-Z]", " ").replaceAll("\s+"," "));


Output :- sharma is a java Developer in CST web but He want to move in another team

Can i do this using single operation? how?

我可以使用单个操作来做到这一点吗?如何?

采纳答案by Cephalopod

Replace any sequence of non-letters with a single whitespace:

用一个空格替换任何非字母序列:

str.replaceAll("[^a-zA-Z]+", " ")

You also might want to apply trim()after the replace.

您可能还想trim()在更换后申请。

If you want to support languages other than english, use "[^\\p{IsAlphabetic}]+"or "[^\\p{IsLetter}]+". See this questionabout the differences.

如果您想支持英语以外的语言,请使用"[^\\p{IsAlphabetic}]+""[^\\p{IsLetter}]+"。请参阅有关差异的问题

回答by Sabuj Hassan

Try this:

尝试这个:

str.replaceAll("[\p{Punct}\s\d]+", " ");

Replacing punctuation, digits and white spaces with a single space.

用一个空格替换标点符号、数字和空格。

回答by TomasZ.

The OR operator | should work:

OR 运算符 | 应该管用:

System.out.println(str.replaceAll("([^a-zA-Z]|\s)+", " "));

Actually, the space doesn't have to be there at all:

实际上,空间根本不必在那里:

System.out.println(str.replaceAll("[^a-zA-Z]+", " "));

回答by Al-Mustafa Azhari

You can use below to remove anything that is not a character (A-Z or a-z) .

您可以使用下面删除任何不是字符 (AZ 或 az) 的内容。

str.replaceAll("[^a-zA-Z]","");