用零填充左边

Nic*_*kon 28 c# regex

我想在我的字符串中用零填充每个数字(它必须是8位数).

例如

asd 123 rete > asd 00000123 rete
4444 my text > 00004444 my text
Run Code Online (Sandbox Code Playgroud)

是否可以使用正则表达式执行此操作?特别是Regex.Replace()

请注意,对于不同的数字,零的数量是不同的.我的意思是填充号码必须是8位数.

Chr*_*ler 71

Microsoft内置了以下功能:

someString = someString.PadLeft(8, '0');
Run Code Online (Sandbox Code Playgroud)

这是一篇关于MSDN的文章

要使用正则表达式,请执行以下操作:

string someText = "asd 123 rete"; 
someText = Regex.Replace(someText, @"\d+", n => n.Value.PadLeft(8, '0'));
Run Code Online (Sandbox Code Playgroud)

  • 这根本不会执行任何拆分. (3认同)

小智 5

线程很旧但也许有人需要这个.

尼克表示他想使用正则表达式.为什么?没关系,也许是它的乐趣.我不得不在SQL中进行内联替换,因此一些调用C#正则表达式的自制SQL函数很有帮助.

我需要填充的内容看起来像这样:

abc 1.1.1
abc 1.2.1
abc 1.10.1
Run Code Online (Sandbox Code Playgroud)

我想要:

abc 001.001.001
abc 001.002.001
abc 001.010.001
Run Code Online (Sandbox Code Playgroud)

所以我可以按字母顺序排序.

到目前为止(我发现)唯一的解决方案是在两个步骤中进行填充和截断到正确的长度.我不能使用Lambda,因为这是在SQL中,我没有为此准备我的函数.

//This pads any numbers and truncates it to a length of 8
var unpaddedData = "...";
var paddedData = Regex.Replace(unpaddedData , "(?<=[^\d])(?<digits>\d+)",
                                                     "0000000${digits}");
var zeroPaddedDataOfRightLength = Regex.Replace(paddedData ,"\d+(?=\d{8})","");
Run Code Online (Sandbox Code Playgroud)

说明:

(?<=[^\d])(?<digits>\d+)
(?<=[^\d])       Look behind for any non digit, this is needed if there are 
                 more groups of numbers that needs to be padded
(?<digits>\d+)   Find the numbers and put them in a group named digits to be 
                 used in the replacement pattern

0000000${digits} Pads all the digits matches with 7 zeros

\d+(?=\d{8})     Finds all digits that are followed by at exactly 8 digits. 
                 ?= Doesn't capture the 8 digits.

Regex.Replace(...,"\d+(?=\d{8})","")   
                 Replaces the leading digits with nothing leaving the last 8.
Run Code Online (Sandbox Code Playgroud)