Wayne L Waag Wayne L Waag - 14 days ago 6
C# Question

Replace leading zeros in timecode string

The host program I am using produces a string timecode as follows:

00:00:01.523


How can I replace leading zeros and change it to the following:

--:--:-1.523

Answer

You can use the Regex.Replace method with a zero-width negative lookbehind assertion:

string input = "00:00:01.523";
string output = Regex.Replace(input, "(?<![1-9].*)0", "-");
// Output: "--:--:-1.523"

The regular expression (?<![1-9].*)0 has two main parts:

  • (?<![1-9].*) is a zero-width negative lookbehind assertion. It verifies that the input string does not match [1-9].* to the left of the current position. (The regular expression [1-9].* matches any digit 1–9, followed by an arbitrary string.)
  • 0 matches the digit 0.

Putting these two parts together, the regular expression as a whole matches any digit 0 that is not preceded by any digit 1–9 — namely, leading zeroes.