Wednesday, July 10, 2013

Masking Credit Card number in Java

Sometimes we need to mask crucial information like Credit Card Numbers, CVV numbers etc before storing  or logging the information. This example mask Credit Card Number (Except last 4 Digit) from a Text which contains information along with Credit Card Number.

The following example demonstrates how we can easily mask the credit card with Matcher and Pattern Classes. This Sample Code uses Matcher and Pattern.
Pattern Used in this sample is not optimized for Credit Card Numbers, this pattern will get any numerical numbers in the String Content.  Based on the Credit Card Type a more efficient and Strict RegEx can be used to mask the Credit Card.

/**Mask the Credit card number but last four digit value **/
         Pattern PATTERN = Pattern.compile("[0-9]+");

        String message = content;
        Matcher matcher = PATTERN.matcher(message);
        String maskingChar = "*";
        StringBuilder finalMask = new StringBuilder(maskingChar);

        while (matcher.find()) {
            String group =;
            int groupLen = group.length();

                for(int i=0; i<=group.length()-4; i++){
            message = message.replace(group, finalMask);
        return message;
If we pass Strings like  This is my Credit Card 11001100032000420035 it will return
This is my Credit Card ******************0035.


  1. Why only mask all but 4 digits

  2. Thank this is what i have been looking ofr

  3. Thanks a lot for this example. It helped me to achieve my task.

    1. Happy that this post helped you. Please also find the github code for this here