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

编程入门 行业动态 更新时间:2024-10-25 16:22:08
本文介绍了在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添加前导零(如果可能的话)?

本文发布于:2023-11-04 00:47:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556497.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:前导   我该   如何使用   Regex   Replace

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!