【问题标题】:Using RegEx how do I remove the trailing zeros and decimal also if needed使用 RegEx 如何在需要时删除尾随零和小数
【发布时间】:2018-03-26 02:23:07
【问题描述】:

我需要删除以下数字上的训练零: 9.2500 = 9.25 感谢@Avinash Raj 以前的帖子,我发现了这个:

^(\d+\.\d*?[1-9])0+$

非常适合该应用程序。但是,在某些情况下,我有一个像 11.0000 这样的数字,上面的 RegEx 返回:

11.0

我需要返回:

11

如果不需要小数点和零,我不确定如何删除?我花了一些时间试图弄清楚,但我很难过。

【问题讨论】:

  • 可以用正则表达式做到这一点并不意味着您应该 ;) 您使用哪种编程语言?
  • @alfasin 我正在使用自动化应用程序。我唯一的清理选项是正则表达式。如果可以使用 java 我就完成了。
  • 鲍勃,你要求一个正则表达式来完成两个不同的任务(你能明白为什么吗?)。另一个想法:运行一次,然后运行另一个正则表达式以更新格式的数字:n.0n
  • @BobTucker 从my old answer 尝试regex。它可能就足够了,或者它可能比你需要的更多。只需选择您需要的替代方案。

标签: regex


【解决方案1】:

试试这个

^\d*\.[1-9]*([0]+)*$

解释

^  beginning of the term
\d*  digits from 0-9 those can be any number (can be 0 number or more)
\.   escaping the .
[1-9]* numbers from 1 to 9 (can be 0 number or more)
([0]+)  capturing all 0s in group1
$  end of the term

Regex101 here

【讨论】:

    【解决方案2】:

    试试这个:

    ^(\d*[\d.]*?)\.?0*$
    

    Regex101 here.

    【讨论】:

      【解决方案3】:
      ^(\d+(?:\.\d*?[1-9](?=0|\b))?)\.?0*$
      

      演示here.


      解释

      ^         //Beginning of line
      (         //Start collecting our group
      \d+       //All digits before decimal
      (?:       //START-Non collecting group
      \.        //Decimal point
      \d*?      //It should actually be [0-9]
      [1-9]     //Last significant digit after decimal
      (?=0|\b)  //Either should be followed by zero or END OF WORD
      )?        //END-Non collecting group
                //The non-capturing group after decimal is optional
      )         //End collecting our group
      \.?       //Optional decimal (decimal collected if it wasn't used earlier)
      0*        //All the remaining zeros no + as all digits might be significant that is no ending zero
      $         //End of line.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-04
        • 2014-09-02
        • 1970-01-01
        • 2011-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多