Search code examples
c#stringc#-4.0trim

c# remove zeros from middle of string


I'm working an a c#-4.0 Windows Form application and I need to remove padding zeros from a serial number.

My serial is stored in a string and looks something like this BMS21-14-000000000000000000120, and the end result I'm after is BMS21-14-120.

The serial number structure is:

  • BMS21 is the prefix.
  • 14 is the production year.
  • 120 is an incrementing number.

Now, the length on our prefix and incrementing numbers will change from product to product, but the structure is consistent. It's always prefix, year and incrementing# and they are always separated by a dash.

I tried following the example outlined by msdn but I couldn't get it to work for our serial numbers.


Solution

  • Here's a one-liner for you:

    var serial = "BMS21-14-000000000000000000120";
    serial = Regex.Replace(serial, @"(?<=-\d+-)0+", String.Empty);
    

    Here's an explanation:

    • 0+ will match a series of zeros.
    • (?<=-\d+-) is a positive lookbehind ((?<=...)). It will assert that what precedes the zeros is a dash, followed by a series of digits (\d+), and another dash. Being an assertion, it won't match anything by itself. \d+ could have been replaced by \d{2} if you wanted to ensure the production year part is made of exactly two digits.

    As a side note, you could add (?=\d) after 0+. It's a positive lookahead that would ensure there's at least one digit left. This would let you reduce BMS21-14-000000000000000000000 to BMS21-14-0 instead of BMS21-14-.