替换不在范围内的所有字符(Java String) [英] Replace all characters not in range (Java String)

查看:456
本文介绍了替换不在范围内的所有字符(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]"

这篇关于替换不在范围内的所有字符(Java String)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆