I have seen Mail services displays the email id's as e*****e@gmail.com
, mostly in their recovery page.
So i am trying to replace the example@gmail.com
as e*****e@gmail.com
.
Is it possible to achieve it using String#replace(String)
alone ? or should i use some REGEX to achieve it .
Thanks for your valuable suggestions in adavance
Search regex:
\b(\w)\S*?(\S)(?=@)(\S+)\b
Replacement Pattern:
$1****$2$3****$4
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
It could be possible through replaceAll function.
(?<!^).(?=.*?.@)
Use the above regex and replace the matched characters with *
String s = "example@gmail.com";
System.out.println(s.replaceAll("(?<!^).(?=.*?.@)", "*"));
Output:
e*****e@gmail.com
Update:
Use the below regex to get the output like e*****e@g***l.com
String s = "example@gmail.com";
System.out.println(s.replaceAll("\\B.\\B(?=.*?\\.)", "*"));
Output:
e*****e@g***l.com
You can try without regex too
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());
Out put:
e*****e@gmail.com
I sugges to use indexOf
and substring
. With replace you can run into tuble with emails like gmail@gmail.com
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.