如何拆分无分隔符且域名后缀各异的邮箱字符串并按指定规则分割?
拆分混合域名邮箱字符串的解决方案
绝对可以搞定这个拆分需求!针对你这种混合了不同顶级域名的邮箱串,正则表达式是最精准的解决方案,完全贴合你提出的拆分规则。
核心思路
我们的目标是:
- 优先识别并拆分出以
.br或.se结尾的完整邮箱 - 对于不满足上述条件的,在
.com结尾处拆分(当.com后紧跟下一个邮箱的@符号时) - 最后兜底处理像
.org这类其他后缀的完整邮箱
具体实现代码
JavaScript 示例
// 原始邮箱字符串 const rawEmailStr = "hello@you.comhi@me.com.secontact@you.com.brcontact@us.org"; // 匹配规则的正则表达式 const emailRegex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+(\.br|\.se|\.com)(?=@|$)|[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.org/g; // 执行匹配拆分 const splitEmails = rawEmailStr.match(emailRegex); console.log(splitEmails); // 输出结果: ["hello@you.com", "hi@me.com.se", "contact@you.com.br", "contact@us.org"]
Python 示例
import re # 原始邮箱字符串 raw_email_str = "hello@you.comhi@me.com.secontact@you.com.brcontact@us.org" # 匹配规则的正则表达式 email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.(?:br|se|com)(?=@|$)|[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.org' # 执行匹配拆分 split_emails = re.findall(email_pattern, raw_email_str) print(split_emails) # 输出结果: ['hello@you.com', 'hi@me.com.se', 'contact@you.com.br', 'contact@us.org']
正则表达式解析
让我们拆解下这个正则的关键部分:
[a-zA-Z0-9._%+-]+:匹配邮箱的用户名部分,符合RFC标准的邮箱用户名允许字符@[a-zA-Z0-9.-]+:匹配@之后的域名主体部分(\.br|\.se|\.com)(?=@|$):匹配.br/.se/.com后缀,并且通过(?=@|$)正向预查确保后缀后要么是下一个邮箱的@符号,要么是字符串结尾,这样就能精准拆分|:逻辑或,兜底匹配.org后缀的完整邮箱(如果还有其他后缀,比如.net,可以直接在这部分补充)
内容的提问来源于stack exchange,提问作者k_osterlund
相关产品推荐
相关产品推荐

