From cfdd043e4ec88d94b145ef7cf3e29622b18dbae7 Mon Sep 17 00:00:00 2001 From: John Date: Wed, 12 Feb 2020 10:48:15 +0800 Subject: [PATCH] add OctStr function for gstr --- text/gstr/gstr_convert.go | 30 +++++++++++++++++++++++++++ text/gstr/gstr_z_unit_convert_test.go | 22 ++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 text/gstr/gstr_convert.go create mode 100644 text/gstr/gstr_z_unit_convert_test.go diff --git a/text/gstr/gstr_convert.go b/text/gstr/gstr_convert.go new file mode 100644 index 000000000..357035b65 --- /dev/null +++ b/text/gstr/gstr_convert.go @@ -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)}) + }, + ) +} diff --git a/text/gstr/gstr_z_unit_convert_test.go b/text/gstr/gstr_z_unit_convert_test.go new file mode 100644 index 000000000..d5d1e3bd4 --- /dev/null +++ b/text/gstr/gstr_z_unit_convert_test.go @@ -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`), "怡") + }) +}