github.com/avicd/go-utilx@v0.1.0/tokx/pair.go (about)

     1  package tokx
     2  
     3  import (
     4  	"strings"
     5  )
     6  
     7  type Pair struct {
     8  	left  string
     9  	right string
    10  }
    11  
    12  func NewPair(left string, right string) *Pair {
    13  	return &Pair{left: left, right: right}
    14  }
    15  
    16  func (it *Pair) Match(text string) bool {
    17  	if text == "" {
    18  		return false
    19  	}
    20  	buf := text
    21  	left := false
    22  	expect := it.left
    23  	for {
    24  		si := strings.Index(buf, expect)
    25  		if si < 0 {
    26  			return false
    27  		} else if si > 0 && buf[si-1] == '\\' {
    28  			buf = buf[si+len(expect):]
    29  			continue
    30  		}
    31  		if left {
    32  			return true
    33  		}
    34  		left = !left
    35  		expect = it.right
    36  	}
    37  }
    38  
    39  func (it *Pair) Map(text string, rel func(s string) string) string {
    40  	if text == "" {
    41  		return text
    42  	}
    43  	buf := text
    44  	left := false
    45  	expect := it.left
    46  	str := &strings.Builder{}
    47  	key := &strings.Builder{}
    48  	for {
    49  		si := strings.Index(buf, expect)
    50  		if si < 0 {
    51  			str.WriteString(buf)
    52  			break
    53  		} else if si > 0 && buf[si-1] == '\\' {
    54  			if left {
    55  				key.WriteString(buf[:si+len(expect)])
    56  			} else {
    57  				str.WriteString(buf[:si+len(expect)])
    58  			}
    59  			buf = buf[si+len(expect):]
    60  			continue
    61  		}
    62  		next := buf[si+len(expect):]
    63  		if left {
    64  			key.WriteString(buf[:si])
    65  			str.WriteString(rel(key.String()))
    66  			key.Reset()
    67  			expect = it.left
    68  		} else {
    69  			str.WriteString(buf[:si])
    70  			expect = it.right
    71  		}
    72  		buf = next
    73  		left = !left
    74  	}
    75  	return str.String()
    76  }