本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.1KB

  1. package match
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. type PrefixSuffix struct {
  7. Prefix, Suffix string
  8. }
  9. func NewPrefixSuffix(p, s string) PrefixSuffix {
  10. return PrefixSuffix{p, s}
  11. }
  12. func (self PrefixSuffix) Index(s string) (int, []int) {
  13. prefixIdx := strings.Index(s, self.Prefix)
  14. if prefixIdx == -1 {
  15. return -1, nil
  16. }
  17. suffixLen := len(self.Suffix)
  18. if suffixLen <= 0 {
  19. return prefixIdx, []int{len(s) - prefixIdx}
  20. }
  21. if (len(s) - prefixIdx) <= 0 {
  22. return -1, nil
  23. }
  24. segments := acquireSegments(len(s) - prefixIdx)
  25. for sub := s[prefixIdx:]; ; {
  26. suffixIdx := strings.LastIndex(sub, self.Suffix)
  27. if suffixIdx == -1 {
  28. break
  29. }
  30. segments = append(segments, suffixIdx+suffixLen)
  31. sub = sub[:suffixIdx]
  32. }
  33. if len(segments) == 0 {
  34. releaseSegments(segments)
  35. return -1, nil
  36. }
  37. reverseSegments(segments)
  38. return prefixIdx, segments
  39. }
  40. func (self PrefixSuffix) Len() int {
  41. return lenNo
  42. }
  43. func (self PrefixSuffix) Match(s string) bool {
  44. return strings.HasPrefix(s, self.Prefix) && strings.HasSuffix(s, self.Suffix)
  45. }
  46. func (self PrefixSuffix) String() string {
  47. return fmt.Sprintf("<prefix_suffix:[%s,%s]>", self.Prefix, self.Suffix)
  48. }
上海开阖软件有限公司 沪ICP备12045867号-1