-2

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}, ...
4

2 回答 2

2

好的,您可以使用一行代码来执行此操作,我花了一些时间才弄清楚如何,但结果如下:

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);

如果有任何问题,请告诉我。

于 2013-08-13T15:05:25.987 回答
0

这是你可以做的:

    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},","****,")));

我希望我能提出一个更好的解决方案。

于 2013-08-13T13:57:41.860 回答