Tone
Tone

Reputation: 783

Regex expression w/ set length

I have several thousands of rows that I'm loading into a database utilizing Pentaho. I must keep the string value length at 4 characters. The source file may only have a single character but it is still needed to keep the length at 4 characters to maintain consistency in the database.

Example:
Source: 10
Database expected results: 0010

I'm using a replace in string transformation or could use a java expression, which ever one works. Please help and provide a resolution utilizing either method (Regex or Javascript expression).

Thanks,

Upvotes: 0

Views: 651

Answers (3)

Hunter McMillen
Hunter McMillen

Reputation: 61510

In Java you can use String.format(...) with a format specifier to pad your number with zeroes to 4 digits:

String.format("%04d", yournumber);

In Javascript you can use sprintf(...) for the same task:

var s = sprintf("%04d", yournumber);

So apparently sprintf() isn't standard Javascript but is a library you can download if you like. You can always to do this to get your 4 digits though:

// take the last 4 digits from the right
var s = String("0000" + yournumber).slice(-4); 

And you could actually turn this into a simple left-padding function:

String.prototype.leftPad = function(paddingValue, paddingLength) {
   return (new Array(paddingLength + 1).join(paddingValue) + this).slice(-paddingLength);
};

var s = String(yournumber).leftPad("0", 4)

Upvotes: 4

SReject
SReject

Reputation: 3936

For arbitrary padding of numbers, in javascript:

// padLeft(
//   number to pad
//   length to pad to
//   character to pad with[optional, uses 0's if not specified]
// )
function padLeft(num, pad, padchr) {
    num = "" + num;
    pad = (pad || num.length) + 1;
    return (num.length < pad ? new Array(pad - num.length).join(padchr || "0") : "") + num;
}

// returns "0010"
var input = 10
padded = padLeft(input, 4) 

Upvotes: 1

Ian
Ian

Reputation: 50905

(If you mean Javascript):

var str = "10";
function padIt(s) {
    s = ""+s;
    while (s.length < 4) {
        s = "0" + s;
    }
    return s;
}
console.log(padIt(str));

http://jsfiddle.net/EzqRM/1/

Upvotes: 1

Related Questions