试图删除所有不是0-9和句号的字母和字符。我使用的是character。isdigit()但它也删除了小数,我怎么能保留小数呢?
当前回答
番石榴:
String input = "abx123.5";
String result = CharMatcher.inRange('0', '9').or(CharMatcher.is('.')).retainFrom(input);
参见http://code.google.com/p/guava-libraries/wiki/StringsExplained
其他回答
试试下面的代码:
String str = "a12.334tyz.78x";
str = str.replaceAll("[^\\d.]", "");
现在str将包含“12.334.78”。
它处理空输入,负数和小数(你需要在你的项目中包含Apache Commons Lang库,版本3.8或更高):
import org.apache.commons.lang3.RegExUtils;
result = RegExUtils.removeAll(input, "-?[^\\d.]");
图书馆参考资料:https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/RegExUtils.html
我会用正则表达式。
String text = "-jaskdh2367sd.27askjdfh23";
String digits = text.replaceAll("[^0-9.]", "");
System.out.println(digits);
打印
2367.2723
你也可以用-来表示负数。
下面的代码应该删除所有非数字字符,并允许句号。
String newString = currentString.replaceAll("[\\D.]", "");
番石榴:
String input = "abx123.5";
String result = CharMatcher.inRange('0', '9').or(CharMatcher.is('.')).retainFrom(input);
参见http://code.google.com/p/guava-libraries/wiki/StringsExplained
推荐文章
- 如何获得具有已知资源名称的资源id ?
- 在Android上将字符串转换为整数
- 为什么“System.out。”println“工作在Android?
- 删除字符串的最后3个字符
- 在Java中什么时候使用可变参数?
- Mockito的argumentCaptor的例子
- 如何大写一个字符串的第一个字母在省道?
- 我如何告诉Spring Boot哪个主类用于可执行jar?
- 如何将Java8流的元素添加到现有的列表中
- 在Java 8中是否可以转换流?
- 不区分大小写的列表排序,没有降低结果?
- 不区分大小写的字符串作为HashMap键
- 什么是maven中的“pom”打包?
- 在Java中创建一个自定义事件
- 创建正则表达式匹配数组