问题描述:

I want to pad left every number with zeroes (it has to be 8 digits) in my string.

e.g.

asd 123 rete > asd 00000123 rete

4444 my text > 00004444 my text

Is it possible to do this using regular expressions? Especially Regex.Replace()?

Notice that the number of zeroes is different for different numbers. I mean the padded number has to be 8 digits long.

网友答案:

Microsoft has built in functions for this:

someString = someString.PadLeft(8, '0');

And here's an article on MSDN

To use a regular expression, do something like this:

string someText = "asd 123 rete"; 
someText = Regex.Replace(someText, @"\d+", n => n.Value.PadLeft(8, '0'));
网友答案:

Thread is old but maybe someone needs this.

Nickon states he wants to use regex. Why? Doesn't matter, maybe its fun. I had to do a inline replace in SQL so some home made SQL functions that calls a C# regex has been helpful.

What I needed to pad looked something like this:

abc 1.1.1
abc 1.2.1
abc 1.10.1

and I wanted:

abc 001.001.001
abc 001.002.001
abc 001.010.001

So I could sort it alphabetiacally.

The only solution so far (that I found) was to do the padding and truncating to right length in two steps. I couldn't use a Lambda since this was in SQL and I hadn't prepared my functions for that.

//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})","");

Explanations:

(?<=[^\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.
网友答案:

If you don't have any attachment to Regex just use format strings:

C# convert int to string with padding zeros?

http://www.xtremedotnettalk.com/showthread.php?t=101461

相关阅读:
Top