xurls.go 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright (c) 2015, Daniel Martí <mvdan@mvdan.cc>
  2. // See LICENSE for licensing information
  3. // Package xurls extracts urls from plain text using regular expressions.
  4. package xurls
  5. import "regexp"
  6. //go:generate go run generate/tldsgen/main.go
  7. //go:generate go run generate/regexgen/main.go
  8. const (
  9. letter = `\p{L}`
  10. number = `\p{N}`
  11. iriChar = letter + number
  12. currency = `\p{Sc}`
  13. otherSymb = `\p{So}`
  14. endChar = iriChar + `/\-+_&~*%=#` + currency
  15. midChar = endChar + `@.,:;'?!|` + otherSymb
  16. wellParen = `\([` + midChar + `]*(\([` + midChar + `]*\)[` + midChar + `]*)*\)`
  17. wellBrack = `\[[` + midChar + `]*(\[[` + midChar + `]*\][` + midChar + `]*)*\]`
  18. wellBrace = `\{[` + midChar + `]*(\{[` + midChar + `]*\}[` + midChar + `]*)*\}`
  19. wellAll = wellParen + `|` + wellBrack + `|` + wellBrace
  20. pathCont = `([` + midChar + `]*(` + wellAll + `|[` + endChar + `])+)+`
  21. comScheme = `[a-zA-Z][a-zA-Z.\-+]*://`
  22. scheme = `(` + comScheme + `|` + otherScheme + `)`
  23. iri = `[` + iriChar + `]([` + iriChar + `\-]*[` + iriChar + `])?`
  24. domain = `(` + iri + `\.)+`
  25. octet = `(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])`
  26. ipv4Addr = `\b` + octet + `\.` + octet + `\.` + octet + `\.` + octet + `\b`
  27. ipv6Addr = `([0-9a-fA-F]{1,4}:([0-9a-fA-F]{1,4}:([0-9a-fA-F]{1,4}:([0-9a-fA-F]{1,4}:([0-9a-fA-F]{1,4}:[0-9a-fA-F]{0,4}|:[0-9a-fA-F]{1,4})?|(:[0-9a-fA-F]{1,4}){0,2})|(:[0-9a-fA-F]{1,4}){0,3})|(:[0-9a-fA-F]{1,4}){0,4})|:(:[0-9a-fA-F]{1,4}){0,5})((:[0-9a-fA-F]{1,4}){2}|:(25[0-5]|(2[0-4]|1[0-9]|[1-9])?[0-9])(\.(25[0-5]|(2[0-4]|1[0-9]|[1-9])?[0-9])){3})|(([0-9a-fA-F]{1,4}:){1,6}|:):[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){7}:`
  28. ipAddr = `(` + ipv4Addr + `|` + ipv6Addr + `)`
  29. site = domain + gtld
  30. hostName = `(` + site + `|` + ipAddr + `)`
  31. port = `(:[0-9]*)?`
  32. path = `(/|/` + pathCont + `?|\b|$)`
  33. webURL = hostName + port + path
  34. strict = `(\b` + scheme + pathCont + `)`
  35. relaxed = `(` + strict + `|` + webURL + `)`
  36. )
  37. var (
  38. // Relaxed matches all the urls it can find.
  39. Relaxed = regexp.MustCompile(relaxed)
  40. // Strict only matches urls with a scheme to avoid false positives.
  41. Strict = regexp.MustCompile(strict)
  42. )
  43. func init() {
  44. Relaxed.Longest()
  45. Strict.Longest()
  46. }
  47. // StrictMatchingScheme produces a regexp that matches urls like Strict but
  48. // whose scheme matches the given regular expression.
  49. func StrictMatchingScheme(exp string) (*regexp.Regexp, error) {
  50. strictMatching := `(\b(?i)(` + exp + `)(?-i)` + pathCont + `)`
  51. re, err := regexp.Compile(strictMatching)
  52. if err != nil {
  53. return nil, err
  54. }
  55. re.Longest()
  56. return re, nil
  57. }