Display email address as a tooltip

I have seen email services display the email id as e*****e@gmail.commainly on the recovery page.

So, I'm trying to replace example@gmail.comwith e*****e@gmail.com.

Is it possible to achieve this using String#replace(String)separately? or should I use some REGEX to achieve it.

Thank you for your valuable suggestions at adavance

+4
source share
4 answers

Search for regex:

\b(\w)\S*?(\S)(?=@)(\S+)\b

Spare Template:

$1****$2$3****$4

RegEx Demo

The code:

String email = "anexample@gmail.com"; 
String repl = email.replaceFirst("\\b(\\w)\\S*?(\\S@)(\\S)\\S*(\\S\\.\\S*)\\b", 
      "$1****$2$3****$4");
//=> a****e@g****l.com
+2
source

This is possible with the replaceAll function.

(?<!^).(?=.*?.@)

*

DEMO

String s = "example@gmail.com";
System.out.println(s.replaceAll("(?<!^).(?=.*?.@)", "*"));

:

e*****e@gmail.com

Update:

, e*****e@g***l.com

String s = "example@gmail.com";
System.out.println(s.replaceAll("\\B.\\B(?=.*?\\.)", "*"));

:

e*****e@g***l.com
+2

You can also try without regex

 String email = "example@gmail.com";
 int start = 1;
 int end = email.indexOf("@") - 1;
 StringBuilder sb = new StringBuilder(email);
 StringBuilder sb1=new StringBuilder();
 for(int i=start;i<end;i++){
    sb1.append("*");
 }
 sb.replace(start, end, sb1.toString());
 System.out.println(sb.toString());

Conclusion:

 e*****e@gmail.com
+2
source

I suggest using indexOfand substring. With a replacement, you may encounter a handset with electronic messages, for examplegmail@gmail.com

+1
source

All Articles