调用re库,通过使用compile、findall获取字符串中的email
import re email=re测试数据pile(r'[a-z0-9\-\.]+@[0-9a-z\-\.]+') emailtest=r'adfasldfjdsl fan02@163测试数据' emailset=set() for em in email.findall(emailtest): ? ? emailset.add(em) for em1 in sorted(emailset): ? ? print(em1)
修改:
通过调用函数,并动态地为字符串赋值
import re def emailre(teststr): ? ? email=re测试数据pile(r'[a-z0-9\-\.]+@[0-9a-z\-\.]+') ? ? emailset=set() ?#列表 ? ? for em in email.findall(teststr): ? ? ? ? emailset.add(em) ? ? for eml in sorted(emailset): ? ? ? ? print(eml) emailtest='sdfdsgf asd03@162测试数据' emailre(emailtest) #或 strtest=r'sdgfsg abc@163测试数据' emailre(strtest)
运行结果:
补充:
从指定的字符串中提取Email:
? /** ? ?* 从指定的字符串中提取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测试数据pile(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测试数据pareToIgnoreCase("a")>=0 && c测试数据pareToIgnoreCase("z")<=0) { ? return true; ?} ?//0-9 ?if (c测试数据pareToIgnoreCase("0")>=0 && c测试数据pareToIgnoreCase("9")<=0) { ?return true; ?} ?//. - _ ?if (c.equals(".") || c.equals("-") || c.equals("_") ) { ?return true; } ?return result;? ?}
到此这篇关于python获取字符串中的email的文章就介绍到这了,更多相关获取字符串中的email内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
查看更多关于python获取字符串中的email的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did99074