简体   繁体   English

替换所有特殊字符,数字和字母

[英]Replacing all special characters, numbers and alphabets

This is the code for example 这是示例代码

String a="abcd ABCD 0123 !@#$%^&*()";

This is syntax for replacing numbers & alphabets with blank 这是用空格替换数字和字母的语法

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

This is syntax for replacing special characters with blank 这是用空格替换特殊字符的语法

a = a.replaceAll("[^\\w\\s-_]","");

So how do I combine both of these syntax to replace special characters, numbers and alphabets with blank without using this method a = a.replaceAll(".",""); 因此,如何将这两种语法结合起来以使用空格替换特殊字符,数字和字母,而不使用此方法a = a.replaceAll(".",""); to replace entire string with blank? 用空白替换整个字符串?

Is there any other way ?? 还有其他办法吗?

I am not sure what you want to achieve, but if you want to combine two character sets you can 我不确定您要实现什么目标,但是如果您想结合使用两个字符集,则可以

  • use OR operator like [oneSet]|[secondSet] 使用OR运算符,例如[oneSet]|[secondSet]
  • place them in other set like [[oneSet][secondSet]] 将它们放置在其他集合中,例如[[oneSet][secondSet]]
    • which can also be simplified to [oneSet[secondSet]] so maybe you are looking for something like 也可以简化为[oneSet[secondSet]]所以也许您正在寻找类似的东西
a = a.replaceAll("[a-zA-Z0-9[^\\w\\s-_]]","");

Demo: I will replace found characters with X to show exactly which characters ware replaced 演示:我将用X替换找到的字符以确切显示商品所替换的字符

String a = "abcd ABCD 0123 !@#$%^&*()";
System.out.println(a.replaceAll("[a-zA-Z0-9]", "X"));
System.out.println(a.replaceAll("[^\\w\\s-_]", "X"));
System.out.println(a.replaceAll("[a-zA-Z0-9[^\\w\\s-_]]", "X"));

Output: 输出:

XXXX XXXX XXXX !@#$%^&*()
abcd ABCD 0123 XXXXXXXXXX
XXXX XXXX XXXX XXXXXXXXXX

Combine with | 结合| :

a=a.replaceAll("[a-zA-Z0-9]|[^\\w\\s-_]", "");

Alternatively you can use below to account for line-breaks 或者,您可以在下面使用它来说明换行符

String s = "abcd ABCD 0123 !@#$%^&*()";
System.out.println(s.replaceAll("(?s)."," "));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM