I have the function which masks credit card numbers in String:
public static String replaceCreditCardNumber(String text){
final String MASKCARD = "$1<MASKED>$2";
final Pattern PATTERNCARD =
Pattern.compile("([0-9]{4})[0-9]{0,9}([0-9]{4})");
Matcher matcher = PATTERNCARD.matcher(text);
if (matcher.find()) {
return matcher.replaceAll(MASKCARD);
}
return text;
}
this function works fine in the following cases:
String text = "Aaaa bbbb aaa=1234567890123456 fdfdfd=aaa";
String expected = "Aaaa bbbb aaa=1234<MASKED>3456 fdfdfd=aaa";
assertEquals(expected,text);//OK
String text = "Aaaa bbbb aaa=\"1234567890123456\" fdfdfd=aaa";
String expected = "Aaaa bbbb aaa=\"1234<MASKED>3456\" fdfdfd=aaa";
assertEquals(expected,text);
However the following case fails
String text = "Aaaa bbbb aaa=1gfg23fgfg4567890123456 fdfdfd=aaa";
String expected = "Aaaa bbbb aaa=1gfg23fgfg4567890123456 fdfdfd=aaa";
assertEquals(expected,text);
I'm getting
aaa=1gfg23fgfg4567[<MASKED>]3456
What am I missing in my regex expression?
You should use word boundaries to make sure to avoid matching unwanted input:
final Pattern PATTERNCARD =
Pattern.compile("\\b([0-9]{4})[0-9]{0,9}([0-9]{4})\\b");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With