如何使用split以外的方法提取邮箱地址中@与.之间的域名前缀部分?
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

