Question

Here is my request string that is currently being printed in the server log.

PaymentRequest{Id=123456, type=CREDIT_CARD, creditCardDetails=CreditCardDetails{type=VISA, name=Some Name, number=1234567890123456, expiry=0316, CCV=000}, directDebitDetails=null}

I want to create a mask for the number field in the above request so that when it is printed in the log it looks like 123456789012--HIDDEN-- (the last 4 digits are replaced with 'HIDDEN').

What java regex to create so that it robustly handles below situations?

  • If [field=value] i.e. number=1234567890123456 is missing in the String.
  • Credit card number could be of any length ranging from 0 to 16 e.g. number= OR number=0 or number=10 or number=1234567890123456.
  • If number is less than 4 than final output is number=--HIDDEN--
  • If number does not present i.e. number= than do nothing.
  • number=1234567890123456 could either be in the middle e.g. ..., name=Some Name, number=1234567890123456}, ... or at last e.g. ..., number=1234567890123456, name=Some Name}, ...
Was it helpful?

Solution

OK you can do this using one line of code and it took me some time to figure out how but here is the result:

String input = "PaymentRequest{Id=123456, type=CREDIT_CARD, creditCardDetails=CreditCardDetails{type=VISA, name=Some Name, number=1234567890123456, expiry=0316, CCV=000}, directDebitDetails=null}"
String result = inputString.replaceAll("(?=number=\\d{1,16},)(number=\\d*?)\\d{1,4},", "$1--HIDDEN--,");
System.out.println(result);

Please let me know if there is any problems.

OTHER TIPS

This is what you can do :

    String num="PaymentRequest{Id=123456, type=CREDIT_CARD, creditCardDetails=CreditCardDetails{type=VISA, name=Some Name, number=1234567890123456, expiry=0316, CCV=000}, directDebitDetails=null}";
    Pattern p = Pattern.compile("number=[0-9]*,");
    Matcher m = p.matcher(num); 
    m.find();
    System.out.println(num.replaceFirst(m.group(), m.group().replaceFirst("[0-9]{4},","****,")));

I wish I could come with a better solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top