【问题标题】:Remove leading zeros with regex but keep minus-sign使用正则表达式删除前导零,但保留减号
【发布时间】:2011-12-15 23:44:03
【问题描述】:

我想用this thread上的这个表达式替换java中的前导零:

s.replaceFirst("^0+(?!$)", "")

但是我怎样才能使它适用于像 -00.8899 这样的值?

【问题讨论】:

    标签: java regex


    【解决方案1】:

    为什么要处理字符串变量中的数值?

    Java 是一种强类型语言,您可能会更轻松地将其转换为浮点数或双精度数,然后执行所有业务逻辑,最后格式化输出。

    类似:

    Double d = Double.parseDouble(s);
    double val = d; //mind the auto-boxing/unboxing
    
    //business logic   
    
    //get ready to display to the user
    DecimalFormat df = new DecimalFormat("#.0000");
    String s = df.format(d);
    

    http://download.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html

    【讨论】:

      【解决方案2】:

      你可以试试:

      String output = "-00.8899".replace("^(-?)0*", "$1");
      

      输出:

      -.8899
      

      【讨论】:

      • 嗨..不错的解决方案。但我也想要正数前的“+”号。例如,双 0.10 应为 +.10,-0.10 应为 -.10,1.0 应为 +1。请为此提供解决方案。
      • @AndiM 试试看:^([-+]?)0*
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-27
      • 2022-07-21
      相关资源
      最近更新 更多