github.com/decred/politeia@v1.4.0/util/regexp.go (about)

     1  // Copyright (c) 2020-2021 The Decred developers
     2  // Use of this source code is governed by an ISC
     3  // license that can be found in the LICENSE file.
     4  
     5  package util
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  	"regexp"
    11  	"strconv"
    12  )
    13  
    14  // Regexp returns a compiled Regexp for the provided parameters.
    15  func Regexp(supportedChars []string, lengthMin, lengthMax uint64) (*regexp.Regexp, error) {
    16  	// Match beginning of string
    17  	var b bytes.Buffer
    18  	b.WriteString("^")
    19  
    20  	// Set allowed character set
    21  	b.WriteString("[")
    22  	for _, v := range supportedChars {
    23  		switch v {
    24  		case `\`, `"`, "[", "]", "^", "-", " ":
    25  			// These characters must be escaped
    26  			b.WriteString(`\` + v)
    27  		default:
    28  			b.WriteString(v)
    29  		}
    30  	}
    31  	b.WriteString("]")
    32  
    33  	// Set min and max length
    34  	min := strconv.FormatUint(lengthMin, 10)
    35  	max := strconv.FormatUint(lengthMax, 10)
    36  	b.WriteString(fmt.Sprintf("{%v,%v}", min, max))
    37  
    38  	// Match end of string
    39  	b.WriteString("$")
    40  
    41  	// Compile regexp
    42  	r, err := regexp.Compile(b.String())
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  
    47  	return r, nil
    48  }