2

Suppose I have string like this ".1.12.3.4.12.4."

As a result I would like to get ".01.12.03.04.12.04."

As you can see, I want all numbers of length == 1 to become of length == 2 with zero at the beginning. How can I achieve this?

4 Answers 4

3

Try this:

var input = ".1.12.3.4.12.4.";
var output = Regex.Replace(input, @"\.(\d)(?=\.)", ".0$1");
Console.WriteLine(output); // .01.12.03.04.12.04.
Sign up to request clarification or add additional context in comments.

3 Comments

this won't match 1.2.4 i.e 1 at the beginning
@Anirudh OP didn't say that it needed to.
thax dude. this is the winner. but all approaches mentioned above also work great. but yours is the shortest :)
1

Split the string into tokens, format each resulting number and then join them back:

var input = ".1.12.3.4.12.4.";
var output = string.Join(
    ".", 
    input.Split('.')
         .Select(i => i.Length == 0 ? "" : i.PadLeft(2, '0'))
);

The best part of this solution is that you can easily change the length of the padded result.

Comments

0

You can do this

Regex.Replace(input,@"(?<=^|[.])(?=\d([.]|$))","0");

Comments

0
string result = string.Join(".", str.Split(".").Select(n => n.Length == 1 ? "0" + n : n));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.