I would 开发者_StackOverflow社区like to add a certain number of leading zeroes to a number in a string. For example:
Input: "page 1", Output: "page 001" Input: "page 12", Ouput: "page 012" Input: "page 123", Ouput: "page 123"
What's the best way to do this with Regex.Replace?
At this moment I use this but the results are 001, 0012, 00123.
string sInput = "page 1";
sInput = Regex.Replace(sInput,@"\d+",@"00$&");
Regex replacement expressions cannot be used for this purpose. However, Regex.Replace
has an overload that takes a delegate allowing you to do custom processing for the replacement. In this case, I'm searching for all numeric values and replacing them with the same value padded to three characters lengths.
string input = "Page 1";
string result = Regex.Replace(input, @"\d+", m => m.Value.PadLeft(3, '0'));
On a sidenote, I do not recommend using Hungarian prefixes in C# code. They offer no real advantages and common style guides for .Net advise against using them.
Use a callback for the replacement, and the String.PadLeft
method to pad the digits:
string input = "page 1";
input = Regex.Replace(input, @"\d+", m => m.Value.PadLeft(3, '0'));
var result = Regex.Replace(sInput, @"\d+", m => int.Parse(m.Value).ToString("00#"));
string sInput = "page 1 followed by page 12 and finally page 123";
string sOutput = Regex.Replace(sInput, "[0-9]{1,2}", m => int.Parse(m.Value).ToString("000"));
string sInput = "page 1";
//sInput = Regex.Replace(sInput, @"\d+", @"00$&");
string result = Regex.Replace(sInput, @"\d+", me =>
{
return int.Parse(me.Value).ToString("000");
});
精彩评论