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.
leftPad() method to left pad a string with zeros, by adding leading zeros to string.
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.
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.
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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With