在C#中,如何使用Regex.Replace添加前导零(如果可能)?

我想在字符串中的数字中添加一定数量的前导零。 例如:

输入:“第1页”,输出:“第001页”输入:“第12页”,输出:“第012页”输入:“第123页”,输出:“第123页”

使用Regex.Replace做到这一点的最佳方法是什么?

此刻我用它但结果是001,0012,00123。

string sInput = "page 1"; sInput = Regex.Replace(sInput,@"\d+",@"00$&"); 

正则表达式替换表达式不能用于此目的。 但是, Regex.Replace有一个重载,它带有一个委托,允许您为替换进行自定义处理。 在这种情况下,我正在搜索所有数值并将其替换为填充为三个字符长度的相同值。

 string input = "Page 1"; string result = Regex.Replace(input, @"\d+", m => m.Value.PadLeft(3, '0')); 

在旁注中,我不建议在C#代码中使用匈牙利语前缀。 它们没有提供真正的优势和.Net建议不使用它们的共同风格指南。

使用回调进行替换,使用String.PadLeft方法填充数字:

 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"); });