![](/img/trans.png)
[英]I have an xml string and I want to to use regex.Replace in C# to add 2 more tags to the exixtsing string. How can i Do that?
[英]In C#, how can I use Regex.Replace to add leading zeroes (if possible)?
我想在字符串中的数字中添加一定数量的前导零。 例如:
输入:“第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");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.