从指定的字符串中提取Email

本文介绍了一个简单的Java程序,该程序能够从给定的文本中提取并验证电子邮件地址的有效性。通过前后扫描找到可能的电子邮件地址,并使用正则表达式进行最终的合法性检查。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  /**
  * 从指定的字符串中提取Email
  * content 指定的字符串
  */
 public static String parse(String content) {
  String email = null;
  if (content==null || content.length()<1) {
   return email;
  }
  //找出含有@
  int beginPos;
  int i;
  String token = "@";
  String preHalf="";
  String sufHalf = "";
 
  beginPos = content.indexOf(token);
  if (beginPos>-1) {
   //前项扫描
   String s = null;
   i= beginPos;
   while(i>0) {
    s = content.substring(i-1,i);
    if (isLetter(s))
     preHalf = s+preHalf;
    else
     break;
    i--;
   }
   //后项扫描
   i= beginPos+1;
   while( i<content.length()) {
    s = content.substring(i,i+1);
    if (isLetter(s))
     sufHalf =  sufHalf +s;
    else
     break;
    i++; 
   }
   //判断合法性
   email = preHalf + "@" + sufHalf;
   if (isEmail(email)) {
    return email;
   }
  }
  return null;
 }
 
 /**
  * 判断是不是合法Email
  * email Email地址
  */
 public static boolean isEmail(String email) {
  try {
   if (email==null || email.length()<1 || email.length()>256) {
    return false;
   }
  
   String check = "^([0-9a-zA-Z]+[_.0-9a-zA-Z-]+)@([a-zA-Z0-9-]+[.])+([a-zA-Z]{2,3})$";
   Pattern regex = Pattern.compile(check);
   Matcher matcher = regex.matcher(email);
   boolean isMatched = matcher.matches();
   if(isMatched) {
    return true;
   } else {
    return false;
   }
  } catch (RuntimeException e) {
   return false;
  }
 }
 
 /**
  * 判断是不是合法字符
  * c 要判断的字符
  */
 public static boolean isLetter(String c) {
  boolean result = false;
 
  if (c==null || c.length()<0) {
   return false;
  }
  //a-z
  if (c.compareToIgnoreCase("a")>=0 && c.compareToIgnoreCase("z")<=0) {
   return true;
  }
  //0-9
  if (c.compareToIgnoreCase("0")>=0 && c.compareToIgnoreCase("9")<=0) {
   return true;
  }
  //. - _
  if (c.equals(".") || c.equals("-") || c.equals("_") ) {
   return true;
  }
  return result;
 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值