简体   繁体   English

为什么replaceAll会从字符串中删除数字?

[英]Why does replaceAll remove the numbers from the String?

String foo = "a3#4#b";
String afterPunctutationRemoval = foo.replaceAll("[,.;:?!'-_\"/()\\{}]", "");
System.out.println(afterPunctutationRemoval);

it gives me "a##b" as a result, can someone explain me why? 它给了我一个“## b”的结果,有人可以解释我为什么吗?

Shouldn't it return the string as it is? 它不应该按原样返回字符串吗?

Your character class contains the range ' .. _ which matches digits as well. 您的角色类包含范围' .. _ ,它也匹配数字。

Put the - at the start or end of the character class: -放在字符类的开头或结尾:

foo.replaceAll("[,.;:?!'_\"/()\\{}-]", "")

or escape it: 或逃避它:

foo.replaceAll("[,.;:?!'\\-_\"/()\\{}]", "");

'-_匹配'_之间'每个字符。

Like the other two people said, escape the - character - \\\\- . 就像其他两个人说的那样,逃避-角色 - \\\\-

Also, \\\\{ evaluates to the same as { , was this intended? 另外, \\\\{评价与{相同,是这个意图吗? If not, try escaping the backslash - \\\\\\\\{ 如果没有,请尝试转义反斜杠 - \\\\\\\\{

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

相关问题 为什么String.replaceAll()在Java 8中与Java 9的工作方式不同? - Why does String.replaceAll() work differently in Java 8 from Java 9? 用replaceAll删除部分字符串 - remove part of string with replaceAll 为什么字符串“:n”被Java中的replaceAll()方法认为与“.n”相同? - Why does the string ":n" considered same as ".n" by replaceAll() method in Java? 为什么这个Java String.replaceAll()代码不起作用? - Why does this Java String.replaceAll() code not work? 为什么 String.replaceAll(".*", "REPLACEMENT") 在 Java 8 中会出现意外行为? - Why does String.replaceAll(".*", "REPLACEMENT") give unexpected behavior in Java 8? 为什么String.replaceAll()的字符需要这么多的转义? - Why does String.replaceAll() need so many escapes for " character? 为什么'replaceAll'方法不在字符串的开头添加空格? - Why does the 'replaceAll' method not add an empty space at the beginning of the String? 如何使用replaceAll从字符串中删除某些html标签? - How to remove certain html tags from a String with replaceAll? 使用replaceAll()从字符串中删除所有两个或多个连续的A - Remove all two or more consecutive A's from a string using replaceAll() string.replaceAll()性能是否受到字符串不变性的影响? - Does string.replaceAll() performance suffer from string immutability?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM