简体   繁体   中英

Replace part of matched string with Regex.Replace

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?

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.

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.

你可以这样做

Regex.Replace(input,@"(?<=^|[.])(?=\d([.]|$))","0");
string result = string.Join(".", str.Split(".").Select(n => n.Length == 1 ? "0" + n : n));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM