github.com/fzfile/BaiduPCS-Go@v0.0.0-20200606205115-4408961cf336/pcsutil/escaper/escaper.go (about) 1 package escaper 2 3 import ( 4 "strings" 5 ) 6 7 type ( 8 // RuneFunc 判断指定rune 9 RuneFunc func(r rune) bool 10 ) 11 12 // EscapeByRuneFunc 通过runeFunc转义, runeFunc返回真, 则转义 13 func EscapeByRuneFunc(s string, runeFunc RuneFunc) string { 14 if runeFunc == nil { 15 return s 16 } 17 18 var ( 19 builder = &strings.Builder{} 20 rs = []rune(s) 21 ) 22 23 for k := range rs { 24 if !runeFunc(rs[k]) { 25 builder.WriteRune(rs[k]) 26 continue 27 } 28 29 if k >= 1 && rs[k-1] == '\\' { 30 builder.WriteRune(rs[k]) 31 continue 32 } 33 builder.WriteString(`\`) 34 builder.WriteRune(rs[k]) 35 } 36 return builder.String() 37 } 38 39 // Escape 转义指定的escapeRunes, 在escapeRunes的前面加上一个反斜杠 40 func Escape(s string, escapeRunes []rune) string { 41 return EscapeByRuneFunc(s, func(r rune) bool { 42 for k := range escapeRunes { 43 if escapeRunes[k] == r { 44 return true 45 } 46 } 47 return false 48 }) 49 } 50 51 // EscapeStrings 转义字符串数组 52 func EscapeStrings(ss []string, escapeRunes []rune) { 53 for k := range ss { 54 ss[k] = Escape(ss[k], escapeRunes) 55 } 56 } 57 58 // EscapeStringsByRuneFunc 转义字符串数组, 通过runeFunc 59 func EscapeStringsByRuneFunc(ss []string, runeFunc RuneFunc) { 60 for k := range ss { 61 ss[k] = EscapeByRuneFunc(ss[k], runeFunc) 62 } 63 }