Advertisement
chrisbailey

RFC822 regular expression

Aug 19th, 2013
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import re
  2.  
  3. # Taken from http://tfletcher.com/lib/rfc822.py
  4. qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]'
  5. dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]'
  6. atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+'
  7. quoted_pair = '\\x5c[\\x00-\\x7f]'
  8. domain_literal = "[\\x5b](?:%s|%s)*[\\x5d]" % (dtext, quoted_pair)
  9. quoted_string = "\\x22(?:%s|%s)*\\x22" % (qtext, quoted_pair)
  10. domain_ref = atom
  11. sub_domain = "(?:%s|%s)" % (domain_ref, domain_literal)
  12. word = "(?:%s|%s)" % (atom, quoted_string)
  13. domain = "%s(?:\\x2e%s)*" % (sub_domain, sub_domain)
  14. local_part = "%s(?:\\x2e%s)*" % (word, word)
  15.  
  16. # Adding maximum length restrictions
  17. addr_spec = "(?=^.{1,256}$)(?=.{1,64}@)%s\\x40%s" % (local_part, domain)
  18.  
  19. email_address = re.compile('^%s$' % addr_spec)
  20.  
  21. if __name__ == '__main__':
  22.     list_of_good = ['somewhere@over.the.rainbow',
  23.                     'SOMEWHERE@over.the.rainbow',
  24.                     'SOMEWHERE@OVER.THE.RAINBOW',
  25.                     'foo@example.com',
  26.                     'paul@io',
  27.                     'foo@bar.example.com',
  28.                     'foo+bar@example.com',
  29.                     'foo.bar@example.com',
  30.                     'foo.bar@[127.0.0.1]',
  31.                     'foo_bar@example.com',
  32.                     'foo-bar@example.com',
  33.                     'cal+henderson@iamcalx.com',
  34.                     '"cal henderson"@iamcalx.com',
  35.                     'cal@[hello world].com',
  36.                     '"foo.bar.@.foo.com"@example.com',
  37.                     ('foo.bar'*9) + '@example.com']
  38.  
  39.     list_of_bad = ['somewhere.over.the.rainbow',
  40.                    'foo..bar@example.com',
  41.                    '.foo@example.com',
  42.                    'bar.@example.com',
  43.                    'foo bar@example.com',
  44.                    'bar@example com',
  45.                    'bar@another example.com',
  46.                    'foo@bar@test@example.com',
  47.                    # Local part can't exceed 64 chars
  48.                    ('foo.bar'*10) + '@example.com',
  49.                    # Total can't exceed 256
  50.                    'foo.bar.foo.bar.foo.bar.bar@' + ('example'*40)]
  51.    
  52.     for t in list_of_good:
  53.         assert email_address.match(t)
  54.    
  55.     for t in list_of_bad:
  56.         assert email_address.match(t) is None
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement