If you're bad at regular expressions, don't use them :) I don't know if you've ever heard the quote:
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.
(source)
You might get a working regular expression here, but will you understand it today? tomorrow? in six months' time? And will your colleagues?
An easy alternative is using a StringBuilder
, and I'd argue that it's a lot more straightforward to understand what is going on here:
StringBuilder sb = new StringBuilder(email);for (int i = 3; i < sb.length() && sb.charAt(i) != '@'; ++i) { sb.setCharAt(i, '*');}email = sb.toString();
"Starting at the third character, replace the characters with a *
until you reach the end of the string or @
."
(You don't even need to use StringBuilder
: you could simply manipulate the elements of email.toCharArray()
, then construct a new string at the end).
Of course, this doesn't work correctly for email addresses where the local part is shorter than 3 characters - it would actually then mask the domain.