Reputation: 11
I am trying to make a function that will do this:
.
at the beginning or at the end of a domain..
in the domain..
in the domain.Like [email protected], it's suppose to make sure it isn't:
[email protected].
[email protected]
and that it is [email protected]
Here is my code for correcting domain:
import re
def correct_domain(domain):
if re.search(r'^\.|.$', domain) and re.search(r'\.\.', domain):
return False
else re.search(r'\.', domain):
return True
Upvotes: 1
Views: 330
Reputation: 129477
This is easy enough to do without a regex:
(domain[0] != '.' != domain[-1] and
'..' not in domain and
'.' in domain)
If you want to exclude cases with two or more periods in general you can try:
domain[0] != '.' != domain[-1] and domain.count('.') == 1
Upvotes: 2
Reputation: 361565
.$
should be \.$
, and and
should be or
. The else
should be elif
, and you should add a final else
clause to handle domains with no dots at all.
if re.search(r'^\.|\.$', domain) or re.search(r'\.\.', domain):
return False
elif re.search(r'\.', domain):
return True
else:
return False
I suggest reorganizing the logic a bit. You can combine the first two reges, for one. You could do it all in one return
statement.
return re.search(r'\.', domain) and not re.search(r'^\.|.$|\.\.', domain):
You could also do these specific checks without regexes, which would be more readable:
return '.' in domain and not \
(domain.startswith('.') or domain.endswith('.') or '..' in domain)
Upvotes: 3
Reputation: 13138
You missed a \
before the second dot; change the and
to an or
:
if re.search(r'^\.|\.$', domain) or re.search(r'\.\.', domain):
Upvotes: 1