Skip to content

Instantly share code, notes, and snippets.

@ariesmcrae
Last active August 20, 2022 08:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ariesmcrae/3bf6cd1722462885ae38be66ea3c4c73 to your computer and use it in GitHub Desktop.
Save ariesmcrae/3bf6cd1722462885ae38be66ea3c4c73 to your computer and use it in GitHub Desktop.
Credit card masker. Any digits between 13 - 16 will be masked.
public static String maskCreditCard(String sentenceThatMightContainACreditCard) {
String maskedSentence = null;
// Find sequence of numbers between 13-16.
// Numbers can have dashes, spaces, or no dashes / no spaces.
Pattern regex = Pattern.compile("\\b(?:\\d[ -]*?){13,16}\\b");
Matcher regexMatcher = regex.matcher(sentenceThatMightContainACreditCard);
if (regexMatcher.find()) {
// Credit card has been found. e.g Here's an Amex: 3782-8224 6310005
String creditCard = regexMatcher.group();
// Strip out spaces and dashes (if any). e.g. 378282246310005
String strippedCreditCard = creditCard.replaceAll("[ -]+", "");
// Take a chunk of the creditcard starting at 7th position,
// ending at the last 4. e.g. 24631
String subSectionOfCreditCard = strippedCreditCard.substring(6, strippedCreditCard.length() - 4);
//Get the first 6 chars of the stripped credit card
String prefix = strippedCreditCard.substring(0, 6);
//Replace the subsection of credit card with 'xxx'
String middle = String.join("", Collections.nCopies(subSectionOfCreditCard.length(), "x"));
//Get the last 4 chars of the stripped credit card
String suffix = strippedCreditCard.substring(strippedCreditCard.length() - 4, strippedCreditCard.length());
// Mask the sub section of the credit card with 'x'. e.g 378282xxxxx0005
String maskedCreditCard = prefix + middle + suffix;
// Take the original text with credit card, and replace the found credit
// card with a masked credit card.
// e.g. 'Market Lane Cafe $4.50 3782-8224 6310005 Large Latte'
// is turned into 'Market Lane Coffee $4.50 378282xxxxx0005 Large Latte'
maskedSentence = sentenceThatMightContainACreditCard.replace(creditCard, maskedCreditCard);
} else {
// If credit card was not found in the text, let's return the original input.
maskedSentence = sentenceThatMightContainACreditCard;
}
return maskedSentence;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment