user8833115566
user8833115566

Reputation: 137

Data masking with specific format

Given a string

"62591000756"

how can I perform masking on the string such that the first 6 character and last 2 character is shown in plain text and the rest is replaced with "X" ? For example,

"625910XXX56"

How can this masking be done in both java code and oracle sql ? Is there any possible way of using regular expression in this case ? ( The number of character is not limited to 11 as shown in the example above )

Upvotes: 0

Views: 1837

Answers (2)

Curiosa Globunznik
Curiosa Globunznik

Reputation: 3205

Another way using replace, available both in java

String text = "62591000756";
String patched = text.substring(0, 6) + "XXX" + text.substring(9);

and sql. It is part of ansi-sql, so it does not depend on your brand of db. Watch out, sql uses 1-based indexing, java is 0-based, java uses the end-index, sql the length of the substring.

String concatenation (the "+") is done in sql using CONCAT (also in the Ansi standard) giving us, let's see...

SELECT CONCAT(SUBSTRING(Fieldname, 1, 6), "XXX", SUBSTRING(Fieldname, 10, 2)) AS PATCHED FROM
Tablename;

Then the java regex version:

"62591000756".replaceAll("([0-9]{6})([0-9]{3})([0-9]{2})", "$1XXX$2")

As for the sql version, depends on your database. Some do regex replace, oracle does.

If you want to generify this to allow for masks of any length at any index, with the regex approach it is at hand: just set custom values for the numbers in the regex ({6}{3}{2}) something like String.format("([0-9]{%d})([0-9]{%d})([0-9]{%d})", lenghtPrefix, lengthMask, lengthPostfix). Note that you'll introduce a lot of corner cases doing so, e.g. index and legth of the mask must be in the range of the original string.

I'm positive you can write a single sql that can handle this, but it might become complex, or, since you're using Oracle, you could write a plsql function for the job which then can be used in sql. Oracle also allows to embed java, never tried this, though.

Upvotes: 1

parthraj panchal
parthraj panchal

Reputation: 121

In java string are immutable so you can't modify string directly but you have to use character Array or you can use StringBuilder. In java using character Array you can do code as below

    String str="62591000756";
    char[] strChar=str.toCharArray();
    int arrLength=strChar.length;
    for(int i=6;i<arrLength-2;i++){
        strChar[i]='X';
    }
    System.out.println(new String(strChar));

This code will output as you want 625910XXX56

Upvotes: 0

Related Questions