Android/Java Regex to remove extra zeros from sub-strings

前端 未结 7 1357
闹比i
闹比i 2020-12-16 17:04

I have the following string as input :

\"2.0,3.00,-4.0,0.00,-0.00,0.03,2.01,0.001,-0.03,101\"

Final output will be like :

         


        
7条回答
  •  长情又很酷
    2020-12-16 17:39

    Using the list of numbers from your question, and some additional ones, the following regex replace will remove all leading and trailing zeros.

    numbers.replaceAll("\\b0*([1-9]*[0-9]+)(\\.[0-9]*[1-9])?\\.?0*\\b", "$1$2");
    

    with input:

    2.0,3.00,-4.0,0.00,-0.00,0.03,2.01,0.001,-0.03,101,101.1010,0020.00

    the result is:

    2,3,-4,0,-0,0.03,2.01,0.001,-0.03,101,101.101,20

    If you want to have decimals without the leading 0 then you can use the following.

    numbers.replaceAll("\\b0*([0-9]+)(\\.[0-9]*[1-9])?\\.?0+\\b|0+(\\.[0-9]+?)0*\\b", "$1$2$3");
    

    with input:

    2.0,3.00,-4.0,0.00,-0.00,0.03,2.01,0.001,-0.03,101,101.1010,0020.00

    the result is:

    2,3,-4,0,-0,.03,2.01,.001,-.03,101,101.101,20

提交回复
热议问题