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

2023-09-04 10:11:08 作者:我在寻找你在逃

我想一定数目的前导零添加到数字的字符串。例如:

I would like to add a certain number of leading zeroes to a number in a string. For example:

输入:第1页,输出:页001 输入:第12页,输出继电器:页012 输入:第123页,输出继电器:第123页

Input: "page 1", Output: "page 001" Input: "page 12", Ouput: "page 012" Input: "page 123", Ouput: "page 123"

什么是与Regex.Replace做到这一点的最好方法是什么?

What's the best way to do this with Regex.Replace?

在这个时刻我用这一点,但结果001,0012,00123。

At this moment I use this but the results are 001, 0012, 00123.

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

推荐答案

的Regex更换前pressions不能用于此目的。然而, Regex.Replace 的过载,需要一个委托让你做定制处理更换。在这种情况下,我在寻找所有的数值和填充三个字符长度相同的值替换它们。

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'));

在一个旁注,我不建议使用匈牙利prefixes在C#code。他们没有提供真正的优势,共同风格指南对于.NET建议不要使用他们。

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.