How to remove leading zeros using C#

前端 未结 8 1488
忘掉有多难
忘掉有多难 2020-12-01 04:16

How to remove leading zeros in strings using C#?

For example in the following numbers, I would like to remove all the leading zeros.

0001234
00000012         


        
8条回答
  •  情话喂你
    2020-12-01 04:26

    This Regex let you avoid wrong result with digits which consits only from zeroes "0000" and work on digits of any length:

    using System.Text.RegularExpressions;
    
    /*
    00123 => 123
    00000 => 0
    00000a => 0a
    00001a => 1a
    00001a => 1a
    0000132423423424565443546546356546454654633333a => 132423423424565443546546356546454654633333a
    */
    
    Regex removeLeadingZeroesReg = new Regex(@"^0+(?=\d)");
    var strs = new string[]
    {
        "00123",
        "00000",
        "00000a",
        "00001a",
        "00001a",
        "0000132423423424565443546546356546454654633333a",
    };
    foreach (string str in strs)
    {
        Debug.Print(string.Format("{0} => {1}", str, removeLeadingZeroesReg.Replace(str, "")));
    }
    

    And this regex will remove leading zeroes anywhere inside string:

    new Regex(@"(? "123432 d=0 p=2 3?574 m=600"
    

提交回复
热议问题