温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎样用java正则提取邮箱

发布时间:2026-09-14 05:54:28 来源:亿速云 阅读:89 作者:小樊 栏目:编程语言

在 Java 中,可以使用 java.util.regex 包中的 正则表达式 来提取字符串中的邮箱地址。下面给你一个实用、常见、可直接用的示例。


一、简单的邮箱正则(常用)

String regex = "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}";

这个正则能匹配绝大多数常见邮箱,例如:

  • test@example.com
  • abc.123@mail.cn
  • user_name@sub.domain.com

二、Java 示例代码(提取所有邮箱)

import java.util.*;
import java.util.regex.*;

public class EmailExtractor {
    public static void main(String[] args) {
        String text = "联系我:test@example.com 或 admin@mail.cn,谢谢!";

        String regex = "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {
            System.out.println(matcher.group());
        }
    }
}

输出结果

test@example.com
admin@mail.cn

三、提取到 List 中(更常用)

public static List<String> extractEmails(String text) {
    List<String> emails = new ArrayList<>();
    String regex = "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}";
    Matcher matcher = Pattern.compile(regex).matcher(text);

    while (matcher.find()) {
        emails.add(matcher.group());
    }
    return emails;
}

四、更严格的邮箱正则(RFC 简化版)

如果你对格式要求更高,可以用:

String strictRegex =
    "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$";

⚠️ 注意:

  • ^ 和 $ 表示整段匹配,提取文本时一般不要加
  • 真正 100% 符合 RFC 的邮箱正则非常复杂,实际项目中不推荐

五、实际建议

✅ 提取邮箱:用宽松正则
✅ 校验用户输入邮箱:可配合 jakarta.validation 或简单正则
❌ 不要试图用一个正则解决所有边界情况


如果你需要:

  • 从 文件 / HTML / 日志 提取邮箱
  • 或做 邮箱去重 / 校验 / 替换

可以告诉我你的具体场景,我可以给你更合适的方案。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手