matchers.nim 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module contains various string matchers for email addresses, etc.
  10. ##
  11. ## **Warning:** This module is deprecated since version 0.14.0.
  12. {.deprecated.}
  13. {.deadCodeElim: on.} # dce option deprecated
  14. {.push debugger:off .} # the user does not want to trace a part
  15. # of the standard library!
  16. include "system/inclrtl"
  17. import parseutils, strutils
  18. proc validEmailAddress*(s: string): bool {.noSideEffect,
  19. rtl, extern: "nsuValidEmailAddress".} =
  20. ## returns true if `s` seems to be a valid e-mail address.
  21. ## The checking also uses a domain list.
  22. const
  23. chars = Letters + Digits + {'!','#','$','%','&',
  24. '\'','*','+','/','=','?','^','_','`','{','}','|','~','-','.'}
  25. var i = 0
  26. if i >= s.len or s[i] notin chars or s[i] == '.': return false
  27. while i < s.len and s[i] in chars:
  28. if i+1 < s.len and s[i] == '.' and s[i+1] == '.': return false
  29. inc(i)
  30. if i >= s.len or s[i] != '@': return false
  31. var j = len(s)-1
  32. if j >= 0 and s[j] notin Letters: return false
  33. while j >= i and s[j] in Letters: dec(j)
  34. inc(i) # skip '@'
  35. while i < s.len and s[i] in {'0'..'9', 'a'..'z', '-', '.'}: inc(i)
  36. if i != s.len: return false
  37. var x = substr(s, j+1)
  38. if len(x) == 2 and x[0] in Letters and x[1] in Letters: return true
  39. case toLowerAscii(x)
  40. of "com", "org", "net", "gov", "mil", "biz", "info", "mobi", "name",
  41. "aero", "jobs", "museum": return true
  42. else: return false
  43. proc parseInt*(s: string, value: var int, validRange: HSlice[int, int]) {.
  44. noSideEffect, rtl, extern: "nmatchParseInt".} =
  45. ## parses `s` into an integer in the range `validRange`. If successful,
  46. ## `value` is modified to contain the result. Otherwise no exception is
  47. ## raised and `value` is not touched; this way a reasonable default value
  48. ## won't be overwritten.
  49. var x = value
  50. try:
  51. discard parseutils.parseInt(s, x, 0)
  52. except OverflowError:
  53. discard
  54. if x in validRange: value = x
  55. when isMainModule:
  56. doAssert "wuseldusel@codehome.com".validEmailAddress
  57. {.pop.}