You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用split以外的方法提取邮箱地址中@与.之间的域名前缀部分?

Alternative Methods to Extract the Middle Domain from an Email

Got it, let's explore a few other ways to pull that target domain segment (like xyz from abc@xyz.com) besides the split-based approach you have. Each method has its own use case, so pick what fits your needs!

1. Regular Expressions (Regex)

Regex is great if you want more control over matching valid email patterns, though for simple cases it's straightforward too. We can craft a pattern that captures the text between @ and the first . after it.

import re

email = "123@helloworld.com"
match = re.search(r'@([^\.]+)\.', email)
if match:
    domain = match.group(1)
    print(domain)  # Output: helloworld

The regex @([^\.]+)\. breaks down to:

  • @: Match the literal "@" character
  • ([^\.]+): Capture one or more characters that aren't a dot (this is our target)
  • \.: Match the literal "." character right after our target segment

2. Using partition()

partition() is safer than split() if you're worried about multiple @ or . characters in the email (though valid emails shouldn't have multiple @s). It splits the string into three parts at the first occurrence of the separator, which makes it predictable.

email = "123@helloworld.com"
# Split at "@" first, take the third part (everything after @)
after_at = email.partition('@')[2]
# Split that result at ".", take the first part
domain = after_at.partition('.')[0]
print(domain)  # Output: helloworld

3. String Indexing with find()

You can manually find the positions of @ and the following ., then slice the string between those indices. This is a bit more low-level but works reliably for simple cases.

email = "123@helloworld.com"
at_pos = email.find('@')
# Find the first "." that comes after the "@"
dot_pos = email.find('.', at_pos)
if at_pos != -1 and dot_pos != -1:
    domain = email[at_pos + 1 : dot_pos]
    print(domain)  # Output: helloworld

We add a check to make sure both @ and . exist in the right order, so we don't get errors if the input isn't a valid email format.


内容的提问来源于stack exchange,提问作者Brian Huynh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 23:22:31