在C#中,我该如何使用Regex.Replace添加前导零(如果可能的话)? [英] In C#, how can I use Regex.Replace to add leading zeroes (if possible)?

查看:326
本文介绍了在C#中,我该如何使用Regex.Replace添加前导零(如果可能的话)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于在C#中,我该如何使用Regex.Replace添加前导零(如果可能的话)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆