- common 的 string.go/array.go/pinyin.go 拆为 stringx 包(含随机串、GUID、 通配符匹配、校验规则、链式缓冲、驼峰转下划线、切片删元素、拼音首字母) - 附单元测试与 examples/stringx 可运行例程、包 README - go.mod 新增直接依赖 mozillazg/go-pinyin(go-hua 同版本锁 v0.20.0→实际解析 v0.21.0)
1.7 KiB
1.7 KiB
stringx
字符串与切片通用工具:随机串、UUID、通配符匹配、中间串提取、手机号/身份证校验、 链式字节缓冲、驼峰转下划线、切片删元素、中文拼音首字母。
迁移自 go-hua/common(原 string.go / array.go / pinyin.go)。
用法
import "git.zeroonesoft.cn/golib/zogo/stringx"
// 随机串(字母数字 / 纯数字 / 十六进制)
stringx.CreateRandomString(16)
stringx.CreateRandomStringInt(6)
stringx.CreateRandomStringHex(8)
// GUID(带连字符)/ UUID(不带连字符),基于 crypto/rand
stringx.GetGUID()
stringx.GetUUID()
// 字符串处理
stringx.GetBetweenStr("key=value&x=1", "key=", "&") // "value"
stringx.Camel2Case("GetUserName") // "get_user_name"
stringx.IsMatchGreed("hello.txt", "*.txt") // true(另有 IsMatchDynamic)
// 校验
stringx.CheckMobile("13812345678")
stringx.CheckIdCard("110101199001011234")
stringx.PhoneCheckRule() // 返回规则正则
stringx.EmailCheckRule()
// 中文拼音首字母(非中文字符原样返回)
stringx.GetFirstLetter("中国") // "zg"
// 切片删除指定下标元素(泛型)
s := stringx.DeleteElement([]int{1, 2, 3, 4, 5}, 2) // [1 2 4 5]
// 链式字节缓冲
b := stringx.NewBuffer()
b.Append("a").Append(1).Append([]byte("b")).Append(rune('c'))
完整可运行例程:examples/stringx/main.go
注意
CreateRandomString*内部rand.Int失败时该位为空字符,正常环境不会发生。GetGUID/GetUUID是随机 UUID(v4 风格),非确定性 UUID;需要标准 RFC 4122 格式请用github.com/google/uuid。- 通配符匹配仅支持
*和?两个通配符。