[英]Replace part of matched string with Regex.Replace
Suppose I have string like this ".1.12.3.4.12.4." 假设我有这样的字符串“ .1.12.3.4.12.4”。
As a result I would like to get ".01.12.03.04.12.04." 结果,我想得到“ .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. 如您所见,我希望所有长度== 1的数字都变成长度== 2且开头为零。 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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.