8

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

  • Z43524429
  • 46D92S429
  • 3488DFJ33

Basically the string can contain alphabet characters or digits. However it cannot contain symbols, just letters and numbers. I would like to mask it so that it looks like this:

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

I've looked everywhere to find an java code example that uses regex to mask this. I've found this post on stack but that assumes that the input is purely a number.

I adjusted the regex to /\w(?=\w{4})/g to include characters as well. It seems to work here. But when I try to implement it in java it doesn't work. Here's the line in my java code:

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

The mask ends up being the same as the accountNumber. So obviously the regex is not working. Any thoughts?

Community
  • 1
  • 1
Richard
  • 5,840
  • 36
  • 123
  • 208

2 Answers2

5

You're using replace, which doesn't use regular expressions.

Try replaceAll.

super_aardvark
  • 1,825
  • 1
  • 14
  • 19
1

Use replaceAll over replace

String mask = accountNumber.replaceAll("\\w(?=\\w{4})", "*");
IQbrod
  • 2,060
  • 1
  • 6
  • 28