Replace emails in string in Java

Ale*_*mez 1 java regex email

I need to protect the email addresses contained in a text. Ideally find a regular expression that could do it more effectively.

Example:

Hi:

My Name is Alex and my mail is alexmail@domain.com but you can reply to
alexreply@other.domain.com.

Desired output:

Hi:

我的名字是 Alex,我的邮件是ale****@domain.com但你可以回复
ale****@other.domain.com

逻辑是:保留前 3 个字符并用 * 替换其余字符,直到@。

a@mail.com     => a****@mail.com
ab@mail.com    => ab****@mail.com
abc@mail.com   => abc****@mail.com
abcd@mail.com  => abc****@mail.com
abcde@mail.com => abc****@mail.com
Run Code Online (Sandbox Code Playgroud)

现在,我以这种方式创建了一个保护邮件的功能,但是当它是一个包含多封电子邮件的文本时,我无法使用replaceAll

public static String protectEmailAddress(String emailAddress) {
     String[] split = emailAddress.split("@");
     if (split[0].length() >= 3) {
         split[0] = split[0].substring(0, 3);  
     }
     emailAddress = StringUtils.join(split, "****@");

     return emailAddress;
}
Run Code Online (Sandbox Code Playgroud)

所以基本上我需要的是一个很好的正则表达式。同样的事情也来,但与邮件的其他部分,如果可能的话。

谢谢...

Cod*_*roc 5

您可以使用 (\\w{1,3})(\\w+)(@.*)

String str = "alexreply@other.domain.com";
str = str.replaceAll("(\\w{1,3})(\\w+)(@.*)", "$1****$3");
System.out.println(str);
Run Code Online (Sandbox Code Playgroud)

输出

ale****@other.domain.com
Run Code Online (Sandbox Code Playgroud)

解释 :

  • (\\w{1,3}) : 匹配 1 到 3 个单词字符
  • (\\w+) : 匹配一个或多个单词字符
  • (@.*) : 匹配之后的任何内容(包括) @
  • $1 : 表示第一组是 (\\w{1,3})
  • $3 : 表示第三组,即 (@.*)