codeeval_challenges / 035_EmailValidation / email_regex.py

#! /usr/bin/env python

import re
import sys
from optparse import OptionParser

LABEL_REGEX = r'[a-zA-Z0-9][a-zA-Z0-9\-]{,63}[a-zA-Z0-9]'

IP_REGEX = r'\[((([1]*[0-9]{1,2})|(2[0-5]{2}))\.){3}(([1]*[0-9]{1,2})|(2[0-5]{2}))\]'

DOMAIN_REGEX = r'(%(label)s\.)*(%(label)s)' % {
    'label': LABEL_REGEX
}

LOCAL_REGEX = '((([a-zA-Z0-9!#\$%&\'\*\+\-\/=\?\^_`\{\|\}\~]*)|(\"[a-zA-z0-9!#\$%&\'\*\+\-\/=\?\^_`\{\|\}\~ \"\(\),:;<>@\[\\]]+\"))\.)*(([a-zA-z0-9!#\$%&\'\*\+\-\/=\?\^_`\{\|\}\~]*)|(\"[a-zA-z0-9!#\$%&\'\*\+\-\/=\?\^_`\{\|\}\~ \"\(\),:;<>@\[\\]]+\"))'

EMAIL_REGEX = r"^((%(local)s)@((%(domain)s)|(%(ip)s)))$" % {
        'local': LOCAL_REGEX,
        'domain': DOMAIN_REGEX,
        'ip': IP_REGEX,
}

def main():

    parser = OptionParser('%s testcase.txt' % __file__)
    options, args = parser.parse_args()

    if len(args) < 1:
        parser.error("No input file provided.")

    test_cases = open(sys.argv[1], 'r')

    for test in test_cases:
        test = test.strip()

        result_bool = False
        compiled = re.compile(EMAIL_REGEX)
        if test != '':
            result = compiled.match(test)
            if result is not None:
                result_bool = (result.group(0) == test)

        print str(result_bool).lower()

    test_cases.close()


if __name__ == "__main__":
    main()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.