regexp.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright (c) 2014 Couchbase, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain 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,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package regexp
  15. import (
  16. "fmt"
  17. "regexp"
  18. "strconv"
  19. "github.com/blevesearch/bleve/analysis"
  20. "github.com/blevesearch/bleve/registry"
  21. )
  22. const Name = "regexp"
  23. var IdeographRegexp = regexp.MustCompile(`\p{Han}|\p{Hangul}|\p{Hiragana}|\p{Katakana}`)
  24. type RegexpTokenizer struct {
  25. r *regexp.Regexp
  26. }
  27. func NewRegexpTokenizer(r *regexp.Regexp) *RegexpTokenizer {
  28. return &RegexpTokenizer{
  29. r: r,
  30. }
  31. }
  32. func (rt *RegexpTokenizer) Tokenize(input []byte) analysis.TokenStream {
  33. matches := rt.r.FindAllIndex(input, -1)
  34. rv := make(analysis.TokenStream, 0, len(matches))
  35. for i, match := range matches {
  36. matchBytes := input[match[0]:match[1]]
  37. if match[1]-match[0] > 0 {
  38. token := analysis.Token{
  39. Term: matchBytes,
  40. Start: match[0],
  41. End: match[1],
  42. Position: i + 1,
  43. Type: detectTokenType(matchBytes),
  44. }
  45. rv = append(rv, &token)
  46. }
  47. }
  48. return rv
  49. }
  50. func RegexpTokenizerConstructor(config map[string]interface{}, cache *registry.Cache) (analysis.Tokenizer, error) {
  51. rval, ok := config["regexp"].(string)
  52. if !ok {
  53. return nil, fmt.Errorf("must specify regexp")
  54. }
  55. r, err := regexp.Compile(rval)
  56. if err != nil {
  57. return nil, fmt.Errorf("unable to build regexp tokenizer: %v", err)
  58. }
  59. return NewRegexpTokenizer(r), nil
  60. }
  61. func init() {
  62. registry.RegisterTokenizer(Name, RegexpTokenizerConstructor)
  63. }
  64. func detectTokenType(termBytes []byte) analysis.TokenType {
  65. if IdeographRegexp.Match(termBytes) {
  66. return analysis.Ideographic
  67. }
  68. _, err := strconv.ParseFloat(string(termBytes), 64)
  69. if err == nil {
  70. return analysis.Numeric
  71. }
  72. return analysis.AlphaNumeric
  73. }