替换不在范围内的所有字符(Java String)

替换不在范围内的所有字符(Java String)

问题描述:

如何替换字符串中不符合条件的所有字符。我在使用NOT运算符时遇到了麻烦。

How do you replace all of the characters in a string that do not fit a criteria. I'm having trouble specifically with the NOT operator.

具体来说,我正在尝试删除所有不是数字的字符,到目前为止我已尝试过:

Specifically, I'm trying to remove all characters that are not a digit, I've tried this so far:

String number = "703-463-9281";
String number2 = number.replaceAll("[0-9]!", ""); // produces: "703-463-9281" (no change)
String number3 = number.replaceAll("[0-9]", "");  // produces: "--" 
String number4 = number.replaceAll("![0-9]", ""); // produces: "703-463-9281" (no change)
String number6 = number.replaceAll("^[0-9]", ""); // produces: "03-463-9281"


解释一下:字符类开头的^将否定该类但它必须在类中才能工作。相反,字符类之外的字符是字符串/行开头的锚点。

To explain: The ^ at the start of a character class will negate that class But it has to be inside the class for that to work. The same character outside a character class is the anchor for start of string/line instead.

您可以尝试这样做:

"[^0-9]"