提取出两个符号之间的内容 & 将第偶数个指定字符换成另一个字符
前端传递如( $124$ && $66$) || $253$ 这样的字符串,我需要解析得到$符之间的数字,不能使用正则。
考虑分成两步:将包裹数字的后一个$替换为#, 即由 ( $124$ && $66$) || $253$ —> ( $124# && $66#) || $253#
再按#切分,提取出数字
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
func GetRuleIdSli(ruleRelation string) (ruleIdSli []string) {
sharpStr := ReplaceRuneInEvenPosition(ruleRelation, '$', '#')
strSli := strings.SplitN(sharpStr, "#", -1)
for _, v := range strSli {
if strings.Contains(v, "$") { pos := strings.Index(v, "$") ruleIdSli = append(ruleIdSli, v[pos+1:]) }
} return }
func ReplaceRuneInEvenPosition(str string, oldRune, newRune uint8) string { var newStr []uint8 j := 0 for i := 0; i < len(str); i++ { c := str[i]
if str[i] == oldRune { j++ if j%2 == 0 { c = newRune } } newStr = append(newStr, c) } return string(newStr) }
|
单元测试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| package utils
import ( "github.com/stretchr/testify/assert" "testing" )
func TestGetRuleIdSli(t *testing.T) {
str := "($124$ && $66$) || $253$"
rs := GetRuleIdSli(str)
expect := []string{"124", "66", "253"}
for k, item := range rs { assert.Equal(t, expect[k], item) }
}
func TestReplaceRuneInEvenPosition(t *testing.T) {
str := "($124$ && $66$) || $253$" rs := ReplaceRuneInEvenPosition(str, '$', '#') assert.Equal(t, "($124# && $66#) || $253#", rs)
}
|
原文链接: https://dashen.tech/2010/03/01/Go生僻字符串操作/
版权声明: 转载请注明出处.