在 Java 中,可以使用 java.util.regex 包中的 正则表达式 来提取字符串中的邮箱地址。下面给你一个实用、常见、可直接用的示例。
String regex = "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}";
这个正则能匹配绝大多数常见邮箱,例如:
test@example.comabc.123@mail.cnuser_name@sub.domain.comimport 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
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;
}
如果你对格式要求更高,可以用:
String strictRegex =
"^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$";
⚠️ 注意:
^和$表示整段匹配,提取文本时一般不要加- 真正 100% 符合 RFC 的邮箱正则非常复杂,实际项目中不推荐
✅ 提取邮箱:用宽松正则
✅ 校验用户输入邮箱:可配合 jakarta.validation 或简单正则
❌ 不要试图用一个正则解决所有边界情况
如果你需要:
可以告诉我你的具体场景,我可以给你更合适的方案。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。