lazyre.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2018 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package lazyregexp is a thin wrapper over regexp, allowing the use of global
  5. // regexp variables without forcing them to be compiled at init.
  6. package lazyregexp
  7. import (
  8. "os"
  9. "regexp"
  10. "strings"
  11. "sync"
  12. )
  13. // Regexp is a wrapper around regexp.Regexp, where the underlying regexp will be
  14. // compiled the first time it is needed.
  15. type Regexp struct {
  16. str string
  17. once sync.Once
  18. rx *regexp.Regexp
  19. }
  20. func (r *Regexp) re() *regexp.Regexp {
  21. r.once.Do(r.build)
  22. return r.rx
  23. }
  24. func (r *Regexp) build() {
  25. r.rx = regexp.MustCompile(r.str)
  26. r.str = ""
  27. }
  28. func (r *Regexp) FindSubmatch(s []byte) [][]byte {
  29. return r.re().FindSubmatch(s)
  30. }
  31. func (r *Regexp) FindStringSubmatch(s string) []string {
  32. return r.re().FindStringSubmatch(s)
  33. }
  34. func (r *Regexp) FindStringSubmatchIndex(s string) []int {
  35. return r.re().FindStringSubmatchIndex(s)
  36. }
  37. func (r *Regexp) ReplaceAllString(src, repl string) string {
  38. return r.re().ReplaceAllString(src, repl)
  39. }
  40. func (r *Regexp) FindString(s string) string {
  41. return r.re().FindString(s)
  42. }
  43. func (r *Regexp) FindAllString(s string, n int) []string {
  44. return r.re().FindAllString(s, n)
  45. }
  46. func (r *Regexp) MatchString(s string) bool {
  47. return r.re().MatchString(s)
  48. }
  49. func (r *Regexp) SubexpNames() []string {
  50. return r.re().SubexpNames()
  51. }
  52. var inTest = len(os.Args) > 0 && strings.HasSuffix(strings.TrimSuffix(os.Args[0], ".exe"), ".test")
  53. // New creates a new lazy regexp, delaying the compiling work until it is first
  54. // needed. If the code is being run as part of tests, the regexp compiling will
  55. // happen immediately.
  56. func New(str string) *Regexp {
  57. lr := &Regexp{str: str}
  58. if inTest {
  59. // In tests, always compile the regexps early.
  60. lr.re()
  61. }
  62. return lr
  63. }