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 15package regexp 16 17import ( 18 "bytes" 19 "fmt" 20 "regexp" 21 22 "github.com/blevesearch/bleve/analysis" 23 "github.com/blevesearch/bleve/registry" 24) 25 26const Name = "regexp" 27 28type CharFilter struct { 29 r *regexp.Regexp 30 replacement []byte 31} 32 33func New(r *regexp.Regexp, replacement []byte) *CharFilter { 34 return &CharFilter{ 35 r: r, 36 replacement: replacement, 37 } 38} 39 40func (s *CharFilter) Filter(input []byte) []byte { 41 return s.r.ReplaceAllFunc(input, func(in []byte) []byte { return bytes.Repeat(s.replacement, len(in)) }) 42} 43 44func CharFilterConstructor(config map[string]interface{}, cache *registry.Cache) (analysis.CharFilter, error) { 45 regexpStr, ok := config["regexp"].(string) 46 if !ok { 47 return nil, fmt.Errorf("must specify regexp") 48 } 49 r, err := regexp.Compile(regexpStr) 50 if err != nil { 51 return nil, fmt.Errorf("unable to build regexp char filter: %v", err) 52 } 53 replaceBytes := []byte(" ") 54 replaceStr, ok := config["replace"].(string) 55 if ok { 56 replaceBytes = []byte(replaceStr) 57 } 58 return New(r, replaceBytes), nil 59} 60 61func init() { 62 registry.RegisterCharFilter(Name, CharFilterConstructor) 63} 64