I want to write a function that parses through an email input and returns a tuple with (id, domain). id is the user name while domain is the domain name. Email separated by @ character
For example: kyle@asu.edu would parse to ('kyle', 'asu.edu'). But below are some additional constraints on the function:
- username begins with alphabetic character
- domain name ends with alphabetic character
- special characters such as ., -, _, or + are allowed
- no whitespace characters permitted including no leading or trailing whitespaces
So if any of the above rules are violated, then the email input is not considered a valid email address and should raise a ValueError.
Below is my attempted code that doesn't quite work:
def email_func(string_input):
"""Parses a string as an email address, returning an (id, domain) pair."""
###
### YOUR CODE HERE
regex_parse = re.search(r'([a-zA-Z_+-.]+)@([a-zA-Z.-]+)', string_input)
# print (regex_parse)
try:
return regex_parse.groups()
except ValueError:
raise ValueError ('not a valid email address')
###
For a simple example it works.
email_func('kyle@asu.edu') returns `('kyle', 'asu.edu')` which is correct.
Instances where my code doesn't work:
For invalid input strings with white spaces I'm not raising a ValueError. For example:
email_func('kyle @asu.edu')
outputs an error:---> 11 return regex_parse.groups()
AttributeError: 'NoneType' object has no attribute 'groups'I'm not getting a ValueError for leading white spaces: For example:
email_func(' kyle@asu.edu')
outputs('kyle', 'asu.edu')
Same issue with trailing white spaces.How do I specify in my regex that the email can't start or end with a number / has to be alphabetic character?