github.com/wuhuizuo/gomplate@v3.5.0+incompatible/funcs/regexp.go (about)

     1  package funcs
     2  
     3  import (
     4  	"sync"
     5  
     6  	"github.com/pkg/errors"
     7  
     8  	"github.com/hairyhenderson/gomplate/conv"
     9  	"github.com/hairyhenderson/gomplate/regexp"
    10  )
    11  
    12  var (
    13  	reNS     *ReFuncs
    14  	reNSInit sync.Once
    15  )
    16  
    17  // ReNS -
    18  func ReNS() *ReFuncs {
    19  	reNSInit.Do(func() { reNS = &ReFuncs{} })
    20  	return reNS
    21  }
    22  
    23  // AddReFuncs -
    24  func AddReFuncs(f map[string]interface{}) {
    25  	f["regexp"] = ReNS
    26  }
    27  
    28  // ReFuncs -
    29  type ReFuncs struct{}
    30  
    31  // Find -
    32  func (f *ReFuncs) Find(re, input interface{}) (string, error) {
    33  	return regexp.Find(conv.ToString(re), conv.ToString(input))
    34  }
    35  
    36  // FindAll -
    37  func (f *ReFuncs) FindAll(args ...interface{}) ([]string, error) {
    38  	re := ""
    39  	n := 0
    40  	input := ""
    41  	switch len(args) {
    42  	case 2:
    43  		n = -1
    44  		re = conv.ToString(args[0])
    45  		input = conv.ToString(args[1])
    46  	case 3:
    47  		re = conv.ToString(args[0])
    48  		n = conv.ToInt(args[1])
    49  		input = conv.ToString(args[2])
    50  	default:
    51  		return nil, errors.Errorf("wrong number of args: want 2 or 3, got %d", len(args))
    52  	}
    53  	return regexp.FindAll(re, n, input)
    54  }
    55  
    56  // Match -
    57  func (f *ReFuncs) Match(re, input interface{}) bool {
    58  	return regexp.Match(conv.ToString(re), conv.ToString(input))
    59  }
    60  
    61  // Replace -
    62  func (f *ReFuncs) Replace(re, replacement, input interface{}) string {
    63  	return regexp.Replace(conv.ToString(re),
    64  		conv.ToString(replacement),
    65  		conv.ToString(input))
    66  }
    67  
    68  // ReplaceLiteral -
    69  func (f *ReFuncs) ReplaceLiteral(re, replacement, input interface{}) (string, error) {
    70  	return regexp.ReplaceLiteral(conv.ToString(re),
    71  		conv.ToString(replacement),
    72  		conv.ToString(input))
    73  }
    74  
    75  // Split -
    76  func (f *ReFuncs) Split(args ...interface{}) ([]string, error) {
    77  	re := ""
    78  	n := -1
    79  	input := ""
    80  	switch len(args) {
    81  	case 2:
    82  		re = conv.ToString(args[0])
    83  		input = conv.ToString(args[1])
    84  	case 3:
    85  		re = conv.ToString(args[0])
    86  		n = conv.ToInt(args[1])
    87  		input = conv.ToString(args[2])
    88  	default:
    89  		return nil, errors.Errorf("wrong number of args: want 2 or 3, got %d", len(args))
    90  	}
    91  	return regexp.Split(re, n, input)
    92  }