Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Replacement lookhead

Tags:

java

regex

I am not able to do a replacement regex

for example I have the email

[email protected]

and I want to replace

f****e@g***l.com

I already got the start

(?<=.).(?=[^@]*?.@)|(?<=\@.).

Below a link from where I am testing

REGEX

like image 938
Felipe Flores Avatar asked Dec 14 '22 20:12

Felipe Flores


2 Answers

With a bit of further tweaking on the pattern, you could achieve that:

"[email protected]".replaceAll("(?<=[^@])[^@](?=[^@]*?.[@.])", "*");

This will give you f****e@g***l.com.

A possibly more efficient, and more readable solution might be finding the indexes of @ and ., and putting together the desired result from substrings:

int atIndex = email.indexOf('@');
int dotIndex = email.indexOf('.');
if (atIndex > 2 && dotIndex > atIndex + 2) {
  String masked = email.charAt(0)
    + email.substring(1, atIndex - 1).replaceAll(".", "*")
    + email.substring(atIndex - 1, atIndex + 2)
    + email.substring(atIndex + 2, dotIndex - 1).replaceAll(".", "*")
    + email.substring(dotIndex - 1);
  System.out.println(masked);
}
like image 170
janos Avatar answered Dec 29 '22 06:12

janos


I found this: (?<=.)([^@])(?!@)(?=.*@)|(?<!@)([^@])(?!.*@)(?!\.)(?=.*\.)

Demo

like image 33
Egan Wolf Avatar answered Dec 29 '22 07:12

Egan Wolf