package strutil
Import Path
github.com/gookit/goutil/strutil (on go.dev)
Dependency Relation
imports 31 packages, and imported by one package
Involved Source Files
bytes.go
check.go
convbase.go
convert.go
encode.go
ext.go
filter.go
format.go
gensn.go
hash.go
padding.go
parse.go
random.go
random_nonwin.go
runes.go
split.go
Package strutil provide some string,char,byte util functions
value.go
Package-Level Type Names (total 10)
Buffer wrap and extends the bytes.Buffer
Builder struct
Builder strings.Builder
Cap returns the capacity of the builder's underlying byte slice. It is the
total space allocated for the string being built and includes any bytes
already written.
Grow grows b's capacity, if necessary, to guarantee space for
another n bytes. After Grow(n), at least n bytes can be written to b
without another allocation. If n is negative, Grow panics.
Len returns the number of accumulated bytes; b.Len() == len(b.String()).
Reset resets the [Builder] to be empty.
ResetGet return current string and reset builder
String returns the accumulated string.
Write bytes and no error report
WriteAny write any type value.
WriteAnys write any type values.
WriteByte appends the byte c to b's buffer.
The returned error is always nil.
WriteByteNE write byte and no error report
WriteMulti write multi byte at once.
WriteRune and no error report
WriteString to builder
WriteStrings write multi string at once.
Writef write string by fmt.Sprintf formatted
Writeln write string with newline.
*Builder : expvar.Var
*Builder : fmt.Stringer
*Builder : io.ByteWriter
ByteChanPool struct
Usage:
bp := strutil.NewByteChanPool(500, 1024, 1024)
buf:=bp.Get()
defer bp.Put(buf)
// use buf do something ...
DateSNOpt 基于时间生成唯一编号
// DateLen 之后的转换 base 2-64. default 36
RandMax int // rand max
// 时间格式长度,后面部分将会进行进制转换 默认 8(yyyyMMdd)
// time layout
EnableSeq bool // 需要高并发生成时可以启用自增序号。默认不启用
// 自增序号最大值,之后后自动重置
GenSN generate date serial number.
func NewDateSNOpt() *DateSNOpt
ParseSizeOpt parse size expression options
KeywordFn is the function for parse keyword time string.
OneAsMax if only one size value, use it as max size. default is false
SepChar is the separator char for time range string. default is '~'
func ParseSizeRange(expr string, opt *ParseSizeOpt) (min, max uint64, err error)
PosFlag type
Runes data slice
PadLeft a rune to want length
PadRight a rune to want length
Padding a rune to want length and with position
SimilarComparator definition
links:
https://github.com/mkideal/cli/blob/master/fuzzy.go
Similar by minDifferRate
Usage:
c := NewComparator("hello", "he")
rate, ok :c.Similar(0.3)
func NewComparator(src, dst string) *SimilarComparator
StrVal string. alias of Value
Value string
Bool convert
Bytes string to bytes
HasPrefix prefix
HasSuffix suffix
Int convert
Int64 convert
IsBlank check
IsEmpty check
IsEndWith suffix
IsStartWith prefix
OrElse string
Set value
Split string
SplitN string
Value string
Val string
WithTrimSpace string and return new
Value : github.com/apache/arrow-go/v18/internal/hashing.ByteSlice
Value : expvar.Var
*Value : flag.Value
Value : fmt.Stringer
func Value.WithTrimSpace() Value
Package-Level Functions (total 256)
AddSlashes add slashes for the string.
AfterFirst get substring after first sep.
AfterLast get substring after last sep.
Align a string by given length and align settings. alias of Resize
AnyToString convert any value to string.
For defaultAsErr:
- False will use fmt.Sprint convert unsupported type
- True will return error on convert fail.
B32Decode base32 decode
B32Encode base32 encode
B64Decode base64 decode
B64DecodeBytes base64 decode
B64Encode base64 encode
B64EncodeBytes base64 encode
Base10Conv convert base10 string to new base string.
BaseConv convert base string by from and to base.
Note: from and to base must be in [2, 64]
Usage:
BaseConv("123", 10, 16) // Output: "7b"
BaseConv("7b", 16, 10) // Output: "123"
BaseConvByTpl convert base string by template.
Usage:
BaseConvert("123", Base62Chars, Base16Chars) // Output: "1e"
BaseConvert("1e", Base16Chars, Base62Chars) // Output: "123"
BaseConvInt convert base int to new base string.
Usage:
BaseConv(123, 16) // Output: "7b"
BaseConvIntByTpl convert base int to new base string.
BeforeFirst get substring before first sep.
BeforeLast get substring before last sep.
BlankOr return default value on val is blank, otherwise return val
Bool parse string to bool. like strconv.ParseBool()
Byte2str convert bytes to string
Byte2string convert bytes to string
BytePos alias of the strings.IndexByte
Camel alias of the CamelCase
CamelCase convert string to camel case.
Support:
"range_price" -> "rangePrice"
"range price" -> "rangePrice"
"range-price" -> "rangePrice"
Compare for two strings.
ConfigSNOpt config default date sn option
ContainsAll given string should contain all substrings. alias of HasAllSubs()
ContainsByte in given string.
ContainsByteOne in given string.
ContainsOne substr(s) in the given string. alias of HasOneSub()
Cut alias of the strings.Cut
DateSN generate date serial number. PREFIX + yyyyMMddHHmmss + ext(微秒+随机数)
DateSNv2 generate date serial number.
- 2 < extBase <= 36
- return: PREFIX + yyyyMMddHHmmss + extBase(6bit micro + 5bit random number)
Example:
- prefix=P, extBase=16, return: P2023091414361354b4490(len=22)
- prefix=P, extBase=36, return: P202309141436131gw3jg(len=21)
DateSNv3 generate date serial number.
- 2 < extBase <= 64
- return: PREFIX + DATETIME(yyyyMMddHHmmss).dateLen + extBase(DATETIME.after+6bit micro + 5bit random number)
- dateLen: 为 DATETIME(yyyyMMddHHmmss) 保留的长度,默认为 8(yyyyMMdd) 后面的给 extBase 使用
Example:
- prefix=P, dateLen=8, extBase=16, return: P202511139vs99gbifnj len: 20
- prefix=P, dateLen=6, extBase=36, return: P2025119yn52qhefati len: 19
- prefix=P, dateLen=6, extBase=48, return: P202511k9ksgD1fe6x len: 18
- prefix=P, dateLen=4, extBase=62, return: P2025aZl8N0y58M7 len: 16
DatetimeNo generate. can use for order-no.
- No prefix, return like: 2023041410484904074285478388(len: 28)
- With prefix, return like: prefix2023041410484904074285478388(len: 28 + len(prefix))
EscapeHTML escape html string
EscapeJS escape javascript string
FilterEmail filter email, clear invalid chars.
FirstLine from command output
GenMd5 Generate a 32-bit md5 string
GlobMatch check for a string match the pattern.
Difference with PathMatch() is: `*` can match any char, contain `/`.
HasAllSubs given string should contain all substrings
HasEmpty value for input strings
HasOnePrefix the string starts with one of the subs
HasOneSub substr(s) in the given string.
HasOneSuffix the string end with one of the subs
HasPrefix substr in the given string.
HasSuffix substr in the given string.
IContains ignore case check substr in the given string.
IContainsAll like ContainsAll(), but ignore case
IContainsOne ignore case check has one substr(s) in the given string.
IEqual ignore case check given two strings are equals.
Implode alias of strings.Join
Indent inserts prefix at the beginning of each non-empty line of s. The
end-of-line marker is NL.
IndentBytes inserts prefix at the beginning of each non-empty line of b.
The end-of-line marker is NL.
Int convert string to int, alias of ToInt()
Int64 convert string to int, will ignore error
Int64Or convert string to int, return default value on fail
Int64OrDefault convert string to int, return default value on fail
Int64OrErr convert string to int, return error on fail
Int64OrPanic convert value to int, will panic on error
IntOr convert string to int, return default value on fail
IntOrDefault convert string to int, return default value on fail
IntOrPanic convert value to int, will panic on error
Ints alias of the ToIntSlice(). default sep is comma(,)
IsAllASCII 判断字符串是否全为可打印 ASCII(无中文等多字节字符)
IsAllEmpty for input strings
IsAlphabet char
IsAlphaNum reports whether the byte is an ASCII letter, number, or underscore
IsBlank returns true if the given string is all space characters.
IsBlankBytes returns true if the given []byte is all space characters.
IsEmpty returns true if the given string is empty.
IsEndOf alias of the strings.HasSuffix
IsEnvName is valid ENV var name. eg: APP_NAME
IsFloat check the string is a float number
IsInt check the string is an integer number
IsLower returns true if the given string is a lowercase, otherwise false.
IsNotBlank returns true if the given string is not blank.
IsNumChar returns true if the given character is a numeric, otherwise false.
IsNumeric returns true if the given string is a numeric(int/float), otherwise false.
IsPositiveNum check the string is a positive number
IsSpace returns true if the given character is a space, otherwise false.
IsSpaceRune returns true if the given rune is a space, otherwise false.
IsStartOf alias of the strings.HasPrefix
IsStartsOf alias of the HasOnePrefix
IsSymbol reports whether the rune is a symbolic character.
IsUint check the string is an unsigned integer number
IsUpper returns true if the given string is an uppercase, otherwise false.
IsUUID check if the string is a valid UUID format.
IsValidUtf8 valid utf8 string check
IsVarName is valid variable name.
IsVersion number. eg: 1.2.0
Join alias of strings.Join
JoinAny type to string
JoinComma quick join strings by comma
JoinList alias of strings.Join
LikeMatch simple check for a string match the pattern. pattern like the SQL LIKE.
Lower alias of the strings.ToLower()
Lowercase alias of the strings.ToLower()
LowerFirst lower first char
LTrim alias of TrimLeft
Ltrim alias of TrimLeft
MatchNodePath check for a string match the pattern.
Use on a pattern:
- `*` match any to sep
- `**` match any to end. only allow at start or end on pattern.
Example:
strutil.MatchNodePath()
Md5 Generate a 32-bit md5 string
MD5 Generate a 32-bit md5 string
Md5Base62 md5 加密原始二进制的转为 base62 字符串,缩短长度(21~22)
Md5Bytes Generate a 32-bit md5 bytes
Md5Simple md5 加密原始二进制的每个byte转为 base62,缩短长度(16)
MicroTimeHexID micro time HEX ID generate.
return like: 643d4cec7db9e(len: 13)
MicroTimeID generate.
- return like: 16074145697981929446(len: 20)
Conv Base:
mtId := MicroTimeID() // eg: 16935349145643425047 len: 20
b16id := Base10Conv(mtId, 16) // eg: eb067252154a9d17 len: 16
b32id := Base10Conv(mtId, 32) // eg: em1jia8akl78n len: 13
b36id := Base10Conv(mtId, 36) // eg: 3ko088phiuoev len: 13
b62id := Base10Conv(mtId, 62) // eg: kb24SKgsQ9V len: 11
MTimeBase36 micro time BASE36 id generate.
MTimeBaseID micro time BASE id generate. toBase: 2-36
Examples:
- toBase=16: 643d4cec7db9e(len: 13)
- toBase=36: hd312z9ka2(len: 10)
MTimeHexID micro time HEX ID generate.
return like: 643d4cec7db9e(len: 13)
MustBool convert to bool and will panic on error
MustCut always returns two substring.
MustInt convert string to int, will panic on error
MustInt64 convert value to int, will panic on error
MustString convert value to string. will panic on error
MustToTime convert date string to time.Time
MustUint convert value to uint, will panic on error. alias of UintOrPanic()
NewBuffer instance, can set init size
NewByteChanPool instance
NewComparator create
NewDateSNOpt create a new DateSNOpt instance.
NewReplacer instance
NoCaseEq check two strings is equals and case-insensitivity
NumVersion parse input string, get valid number version. eg: go-1.22.3 -> 1.22.3
OrCond return s1 on cond is True, OR return s2.
Like: cond ? s1 : s2
OrElse return default value on s is empty, otherwise return s
OrElseNilSafe return default value on s is nil, otherwise return s
OrHandle return fn(s) on s is not empty.
PadBytes padding a byte to want length and with position flag
PadBytesLeft a byte to want length
PadBytesRight a byte to want length
Padding Fill the string to the specified length.
params:
- s: 原始字符串
- pad: 用于填充的字符或字符串
- length: 目标长度
- padPos: 填充位置标志(左填充或右填充)
PadLeft a string.
PadRight a string.
PadRunes padding a rune to want length and with position flag
PadRunesLeft a rune to want length
PadRunesRight a rune to want length
ParseSizeRange parse range size expression to min and max size.
Expression format:
"1KB~2MB" => 1KB to 2MB
"-1KB" => <1KB
"~1MB" => <1MB
"< 1KB" => <1KB
"1KB" => >1KB
"1KB~" => >1KB
">1KB" => >1KB
"+1KB" => >1KB
PathMatch check for a string match the pattern. alias of the path.Match()
TIP: `*` can match any char, not contain `/`.
QuickMatch check for a string. pattern can be a substring.
QuietBool convert to bool, will ignore error
QuietCut always returns two substring.
QuietInt convert string to int, will ignore error
QuietInt64 convert string to int, will ignore error
QuietString convert value to string, will ignore error. same as SafeString()
Quote alias of strings.Quote
RandomBytes generate
RandomChars generate give length random chars at `a-z`
RandomCharsV2 generate give length random chars in `0-9a-z`
RandomCharsV3 generate give length random chars in `0-9a-zA-Z`
RandomString generate.
Example:
// this will give us a 44 byte, base64 encoded output
token, err := RandomString(16) // eg: "I7S4yFZddRMxQoudLZZ-eg"
RandWithTpl generate random string with give template
Repeat a string by given times.
RepeatBytes repeat a byte char.
RepeatRune repeat a rune char.
Replaces replace multi strings
pairs: {old1: new1, old2: new2, ...}
Can also use:
strings.NewReplacer("old1", "new1", "old2", "new2").Replace(str)
ReplaceVars replaces simple variables in a string. format: {varName}
Usage:
strutil.ReplaceVars("{name}, age is {age}", map[string]string{
"name": "Joe",
"age": "18"
})
Resize a string by given length and align settings. use padding space.
If len(s) > wantLen, will truncate it.
Rtrim alias of TrimRight
RTrim alias of TrimRight
RuneCount of the string.
Examples:
str := "hi,你好"
len(str) // 9
strutil.RunesWidth(str) // 7 一个中文字占两个字符
RuneCount(str) = utf8.RuneCountInString(s) // 5 按字算
RuneIsLower char
RuneIsUpper char
RuneIsWord char: a-zA-Z
RunePos alias of the strings.IndexRune
RunesWidth utf8 runes string width.
Examples:
str := "hi,你好"
len(str) // 9
strutil.RunesWidth(str) // 7 一个中文字占两个字符
len([]rune(str)) = utf8.RuneCountInString(s) // 5 按字算
RuneWidth of the rune.
Example:
RuneWidth('你') // 2
RuneWidth('a') // 1
RuneWidth('\n') // 0
SafeBool convert to bool and will ignore error
SafeByteSize converts size string like 1GB/1g or 12mb/12M into an unsigned integer number of bytes
SafeInt convert string to int, will ignore error
SafeInt64 convert string to int, will ignore error
SafeString convert value to string. Will ignore error
SafeUint convert string to uint, will ignore error
ShortMd5 Generate a 16-bit md5 string. remove the first 8 and last 8 bytes from 32-bit md5 string.
ShortUUID Generate a short UUID (8 characters)
Similarity calc for two string.
Usage:
rate, ok := Similarity("hello", "he")
SimpleMatch all substring in the give text string.
Difference the ContainsAll:
- start with ^ for exclude contains check.
- end with $ for the check end with keyword.
SnakeCase convert. eg "RangePrice" -> "range_price"
Split string to slice. will trim each item and filter empty string node.
SplitByWhitespace Separate strings by whitespace characters (space, TAB, newline, etc.)
SplitInlineComment for an inline text string. default is strict mode.
SplitKV split string to key and value.
SplitN string to slice. will filter empty string node.
SplitNTrimmed split string to slice.
will trim space for each node, but not filter empty
SplitNValid string to slice. will filter empty string node.
SplitTrimmed split string to slice.
will trim space for each node, but not filter empty
SplitValid string to slice. will trim each item and filter empty string node.
String convert value to string, return error on failed
StringOr convert any value to string, return default value on failed
StringOrDefault convert any value to string, return default value on failed
StringOrErr convert value to string, return error on failed
StringOrPanic convert value to string, will panic on error
Strings alias of the ToSlice()
StripSlashes strip slashes for the string.
StrPos alias of the strings.Index
Substr for a string. NOTE: strLn := len(runes)
if length <= 0, return pos to end.
SubstrCount returns the number of times the substr substring occurs in the s string.
Actually, it comes from strings.Count().
- s The string to search in
- substr The substring to search for
- params[0] The offset where to start counting.
- params[1] The maximum length after the specified offset to search for the substring.
TextSplit alias of the Utf8Split()
TextTruncate alias of the Utf8Truncate()
TextWidth utf8 string width. alias of RunesWidth()
TextWrap a string by "\n". alias of the WidthWrap()
Title alias of the strings.ToTitle()
ToArray alias of the ToSlice()
ToBool convert string to bool
ToBytes convert string to bytes
ToByteSize converts size string like 1GB/1g or 12mb/12M into an unsigned integer number of bytes
ToDuration parses a duration string. such as "300ms", "-1.5h" or "2h45m".
Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
ToInt convert string to int, return error on fail
ToInt64 convert string to int, return error on fail
ToInts alias of the ToIntSlice(). default sep is comma(,)
ToIntSlice split string to slice and convert item to int.
Default sep is comma
ToSlice split string to array.
ToString convert value to string, return error on failed
ToStrings alias of the ToSlice()
ToStringWith try to convert value to string. can with some option func, more see comfunc.ConvOption.
ToTime convert date string to time.Time
NOTE: always use local timezone.
ToTimeIn convert date string to time.Time with location.
ToUint convert string to uint, return error on fail. alias of UintOrErr()
Trim string. if cutSet is empty, will trim SPACE.
TrimCut always returns two substring and trim space for items.
TrimLeft char in the string. if cutSet is empty, will trim SPACE.
TrimRight char in the string. if cutSet is empty, will trim SPACE.
Truncate alias of the Utf8Truncate()
Uint convert string to uint, will ignore error
UintOr convert string to uint, return default value on fail
UintOrDefault convert string to uint, return default value on fail
UintOrErr convert string to uint, return error on fail
UintOrPanic convert value to uint, will panic on error
Unquote remove start and end quotes by single-quote or double-quote
tip: strconv.Unquote cannot unquote single-quote
Upper alias of the strings.ToUpper()
Uppercase alias of the strings.ToUpper()
UpperFirst upper first char
UpperWord Change the first character of each word to uppercase
URLDecode decode url string.
URLEncode encode url string.
Utf8Align a string by given length and align settings. alias of Utf8Resize
Utf8len count rune of the string.
Utf8Len count rune of the string.
Examples:
str := "hi,你好"
len(str) // 9
strutil.RunesWidth(str) // 7 一个中文字占两个字符
RuneCount(str) = Utf8Len(s) // 5 按字算
Utf8Padding Fill the string to the specified length. use utf8 width.
Utf8Resize a string by given length and align settings. use padding space.
If width(s) > wantLen, will truncate it.
Utf8Split split a string by width.
Utf8Truncate a string with given width.
Utf8Width utf8 string width. alias of RunesWidth
UUIDv4 Generate a simple UUIDv4 string
Valid return first not empty element.
VersionCompare for two version strings. eg: 1.2.0 > 1.1.0
WidthWrap a string by "\n"
Example:
s := "hello 你好, world 世界"
s1 := strutil.TextWrap(s, 6) // "hello \n你好, \nworld \n世界"
WordWrap text string and limit width.
WrapTag for given string.
Type Parameters:
T: ~string
ZeroOr return default value on val is zero, otherwise return val. same of OrElse()
Package-Level Variables (total 18)
base32 encoding with no padding
base32 encoding with no padding
B64Std base64 encoding with no padding
global id:
https://github.com/rs/xid
https://github.com/satori/go.uuid
global id:
https://github.com/rs/xid
https://github.com/satori/go.uuid
Equal check, alias of strings.EqualFold
ErrDateLayout error
ErrInvalidParam error
ErrInvalidSizeExpr invalid size expression error
InArray alias of HasOneSub()
IsVariableName alias for IsVarName
methods aliases
methods aliases
StartsWith alias func for HasPrefix
StartsWithAny alias of the HasOnePrefix
methods aliases
methods aliases
Package-Level Constants (total 18)
some constant string chars
some constant string chars
AlphaNum chars, can use for base36 encode
AlphaNum2 chars, can use for base62 encode
some constant string chars
const Base10Chars = "0123456789" const Base16Chars = "0123456789abcdef" const Base32Chars = "0123456789abcdefghjkmnpqrstvwxyz" const Base36Chars = "0123456789abcdefghijklmnopqrstuvwxyz" const Base48Chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL" const Base62Chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" const Base64Chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/"
some constant string chars
some constant string chars
Position for padding/resize string
Position for padding/resize string
Position for padding/resize string
Position for padding/resize string
![]() |
The pages are generated with Golds v0.8.4. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds. |