Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pad left with zeroes

Tags:

c#

regex

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.

like image 646
Nickon Avatar asked Aug 10 '12 12:08

Nickon


People also ask

How can I pad a string with zeros on the left?

leftPad() method to left pad a string with zeros, by adding leading zeros to string.

What is a zero padded number?

Zero padding is a technique typically employed to make the size of the input sequence equal to a power of two. In zero padding, you add zeros to the end of the input sequence so that the total number of samples is equal to the next higher power of two.

How do you pad your output's leading digits with zeros?

The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.


1 Answers

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')); 
like image 130
Chris Gessler Avatar answered Oct 11 '22 11:10

Chris Gessler