Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex to mask alphanumeric string and show last 4 digits

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?

like image 650
Richard Avatar asked Oct 08 '15 17:10

Richard


People also ask

How to get last 4 characters of a string in Java?

To extract last n characters, simply print (length-n)th character to nth character using the charAt() method.

How do you replace characters except last with the specified mask character in Java?

We use some inbuilt JavaScript function slice to slice our given string here we write slice(0,-n) where -n will skip the last n character of the string. Then we use replace function to replace the character with a specified mask. Replace all characters we use regex /./g where '.

How to get last 2 letters of string in Java?

For example, to get last two characters of a string, using method substring(input. length() - 2) .

How do I check if a string is alphanumeric regex?

For checking if a string consists only of alphanumerics using module regular expression or regex, we can call the re. match(regex, string) using the regex: "^[a-zA-Z0-9]+$". re. match returns an object, to check if it exists or not, we need to convert it to a boolean using bool().


1 Answers

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

Try replaceAll.

like image 69
super_aardvark Avatar answered Sep 18 '22 10:09

super_aardvark