Java Regex to mask an alphanumeric string and display the last 4 digits

I have an input line that looks like any of the following:

  • Z43524429
  • 46D92S429
  • 3488DFJ33

Basically, a string can contain alphabetical characters or numbers. However, it cannot contain characters, just letters and numbers. I would like to disguise it so that it looks like this:

  • ***** 4429
  • ***** S429
  • ***** FJ33

I searched everywhere to find sample Java code that uses regex to mask this. I found this post on the stack, but this suggests that the input is purely a number.

I adjusted the regex to /\w(?=\w{4})/g to include characters. Seems to work here . But when I try to implement it in java, this will not work. Here is the line in my java code:

 String mask = accountNumber.replace("\\w(?=\\w{4})", "*"); 

The mask ends with the same account number. Obviously, regex doesn't work. Any thoughts?

+7
java string regex masking
source share
1 answer

You are using replace , which does not use regular expressions.

Try replaceAll .

+5
source share

All Articles