Regex-replace
(?<=^|\.)0+
with an empty string. Regular expression:
(? <= # begin positive look-behind (ie "a position preceded by")
^ | \. # the start of the string or a literal dot β
) # end positive look-behind
0+ # one or more "0" characters
β Note that not all regular expression flavors support a variable-length look, but .NET does.
If you expect this type of input: "00.03.03" and want to keep the leading zero in this case (for example, "0.3.3" ), use this expression:
(?<=^|\.)0+(?=\d)
and replace the empty string again.
From the comments (thanks to Kobi): There is a more concise expression that does not require appearance and is equivalent to my second sentence:
\b0+(?=\d)
which the
\ b # a word boundary (a position between a word char and a non-word char)
0+ # one or more "0" characters
(? = \ d) # positive look-ahead: a position that followed by a digit
This works because 0 is a word character, so word boundaries can be used to find the first 0 in a string. This is a more compatible expression because many regex flavors do not support variable-length looks, and some (like JavaScript) do not look at all.
Tomalak
source share