add OctStr function for gstr

This commit is contained in:
John
2020-02-12 10:48:15 +08:00
parent 78917ed5cb
commit cfdd043e4e
2 changed files with 52 additions and 0 deletions

30
text/gstr/gstr_convert.go Normal file
View File

@ -0,0 +1,30 @@
// Copyright 2019 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gstr
import (
"regexp"
"strconv"
)
var (
// octReg is the regular expression object for checks octal string.
octReg = regexp.MustCompile(`\\[0-7]{3}`)
)
// OctStr converts string container octal string to its original string,
// for example, to Chinese string.
// Eg: `\346\200\241` -> 怡
func OctStr(str string) string {
return octReg.ReplaceAllStringFunc(
str,
func(s string) string {
i, _ := strconv.ParseInt(s[1:], 8, 0)
return string([]byte{byte(i)})
},
)
}

View File

@ -0,0 +1,22 @@
// Copyright 2019 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
// go test *.go -bench=".*"
package gstr_test
import (
"testing"
"github.com/gogf/gf/test/gtest"
"github.com/gogf/gf/text/gstr"
)
func Test_OctStr(t *testing.T) {
gtest.Case(t, func() {
gtest.Assert(gstr.OctStr(`\346\200\241`), "怡")
})
}