【问题标题】:Java, replace string numbers with blankstring and remove everything after the numbersJava,用空白字符串替换字符串数字并删除数字后面的所有内容
【发布时间】:2013-02-25 03:35:55
【问题描述】:

我有这样的字符串:

Alian 12WE 

ANI1451

有没有办法在 JAVA 中用空字符串替换所有数字(以及数字后面的所有内容)?

我希望输出如下所示:

Alian

ANI

【问题讨论】:

  • 使用正则表达式搜索数字的第一个索引,然后使用substring(0,index) .. google 一下如何在java中使用正则表达式和子字符串方法。享受编码:)

标签: java regex replace


【解决方案1】:

使用正则表达式非常简单:

public class Test {

    public static String replaceAll(String string) {
        return string.replaceAll("\\d+.*", "");
    }

    public static void main(String[] args) {
        System.out.println(replaceAll("Alian 12WE"));
        System.out.println(replaceAll("ANI1451"));
    }   
}

【讨论】:

    【解决方案2】:

    使用正则表达式

    "Alian 12WE".split("\\d")[0] // Splits the string at numbers, get the first part.
    

    或者将"\\d.+$"替换为""

    【讨论】:

    • 添加.trim() 删除尾随空格
    • 看示例输出:Alian
    【解决方案3】:

    您可以在找到数字后使用正则表达式删除所有内容 - 类似于:

    String s = "Alian 12WE";
    s = s.replaceAll("\\d+.*", "");
    
    • \\d+ 找到一个或多个连续数字
    • .* 匹配数字后的任何字符

    【讨论】:

      猜你喜欢
      • 2014-08-26
      • 1970-01-01
      • 2010-12-20
      • 1970-01-01
      • 2012-10-19
      • 2010-12-01
      • 1970-01-01
      • 2012-03-08
      • 2011-11-23
      相关资源
      最近更新 更多