Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex - mask credit card number

Tags:

java

string

regex

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?

like image 400
danny.lesnik Avatar asked Jan 30 '26 15:01

danny.lesnik


1 Answers

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

Working Demo

like image 171
anubhava Avatar answered Feb 02 '26 06:02

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!