【问题标题】:How to filter out numbers from a string in java?如何从java中的字符串中过滤掉数字?
【发布时间】:2013-10-04 20:46:01
【问题描述】:

我有一个如下形式的字符串,例如 -:

String str = "The game received average review scores of 96.92% and 98/100 for the Xbox 360 version";

我希望输出如下 -:

Output = "The game received average review scores of % and / for the Xbox version"

并且我希望能够过滤掉字符串中的任何数字,无论是十进制数还是浮点数,我尝试使用蛮力的方式来执行此操作 -:

String str = "The game received average review scores of 96.92% and 98/100 for the Xbox 360 version";

String newStr = "";

for(int i = 0 ; i < str.length() ; ++i){
if(!Character.isDigit(str.charAt(i)))
   newStr += str.charAt(i);
}

System.out.println(newStr);

但这并没有解决我的目的,如何解决这个问题?

【问题讨论】:

  • 您可以查看this answer,这与您要查找的内容基本相反。通过一些调整,您可以使用它。

标签: java regex string


【解决方案1】:

您可以使用以下 String#replaceAll 调用将所有数字(后跟 0 个或多个空格)替换为空字符串:

str.replaceAll("\\d+(,\\d+)*(?:\\.\\d+)?\\s*", "");

【讨论】:

  • 这不适用于这样的字符串:“App Store 提供了超过 775,000 个由 Apple 和第三方提供的应用程序。”它在两者之间留下一个“,”
  • 你的例子还有%/留在字符串中。
【解决方案2】:

你也许可以使用这样的东西:

str.replaceAll("\\d+(?:[.,]\\d+)*\\s*", "");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 2022-01-02
    • 1970-01-01
    • 2018-09-28
    • 2013-06-14
    • 1970-01-01
    相关资源
    最近更新 更多