regex.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2013 com authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. // License for the specific language governing permissions and limitations
  13. // under the License.
  14. package com
  15. import "regexp"
  16. const (
  17. regex_email_pattern = `(?i)[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}`
  18. regex_strict_email_pattern = `(?i)[A-Z0-9!#$%&'*+/=?^_{|}~-]+` +
  19. `(?:\.[A-Z0-9!#$%&'*+/=?^_{|}~-]+)*` +
  20. `@(?:[A-Z0-9](?:[A-Z0-9-]*[A-Z0-9])?\.)+` +
  21. `[A-Z0-9](?:[A-Z0-9-]*[A-Z0-9])?`
  22. regex_url_pattern = `(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?`
  23. )
  24. var (
  25. regex_email *regexp.Regexp
  26. regex_strict_email *regexp.Regexp
  27. regex_url *regexp.Regexp
  28. )
  29. func init() {
  30. regex_email = regexp.MustCompile(regex_email_pattern)
  31. regex_strict_email = regexp.MustCompile(regex_strict_email_pattern)
  32. regex_url = regexp.MustCompile(regex_url_pattern)
  33. }
  34. // validate string is an email address, if not return false
  35. // basically validation can match 99% cases
  36. func IsEmail(email string) bool {
  37. return regex_email.MatchString(email)
  38. }
  39. // validate string is an email address, if not return false
  40. // this validation omits RFC 2822
  41. func IsEmailRFC(email string) bool {
  42. return regex_strict_email.MatchString(email)
  43. }
  44. // validate string is a url link, if not return false
  45. // simple validation can match 99% cases
  46. func IsUrl(url string) bool {
  47. return regex_url.MatchString(url)
  48. }