strutil

package
v0.6.15 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 4, 2024 License: MIT Imports: 29 Imported by: 123

README

String Util

This is a go string operate util package.

Install

go get github.com/gookit/goutil/strutil

Usage

ss := strutil.ToArray("a,b,c", ",")
// Output: []string{"a", "b", "c"}

ints, err := strutil.ToIntSlice("1,2,3")
// Output: []int{1, 2, 3}

Functions

func AddSlashes(s string) string
func AnyToString(val interface{}, defaultAsErr bool) (str string, err error)
func B32Decode(str string) string
func B32Encode(str string) string
func B64Decode(str string) string
func B64Encode(str string) string
func Base64(str string) string
func Bool(s string) (bool, error)
func Byte2str(b []byte) string
func Byte2string(b []byte) string
func BytePos(s string, bt byte) int
func Camel(s string, sep ...string) string
func CamelCase(s string, sep ...string) string
func Compare(s1, s2, op string) bool
func Cut(s, sep string) (before string, after string, found bool)
func EscapeHTML(s string) string
func EscapeJS(s string) string
func FilterEmail(s string) string
func GenMd5(src interface{}) string
func HasAllSubs(s string, subs []string) bool
func HasOnePrefix(s string, prefixes []string) bool
func HasOneSub(s string, subs []string) bool
func HasPrefix(s string, prefix string) bool
func HasSuffix(s string, suffix string) bool
func Implode(sep string, ss ...string) string
func Indent(s, prefix string) string
func IndentBytes(b, prefix []byte) []byte
func Int(s string) (int, error)
func Int64(s string) int64
func Int64OrErr(s string) (int64, error)
func Int64OrPanic(s string) int64
func IntOrPanic(s string) int
func Ints(s string, sep ...string) []int
func IsAlphaNum(c uint8) bool
func IsAlphabet(char uint8) bool
func IsBlank(s string) bool
func IsBlankBytes(bs []byte) bool
func IsEmpty(s string) bool
func IsEndOf(s, suffix string) bool
func IsNotBlank(s string) bool
func IsNumChar(c byte) bool
func IsNumeric(s string) bool
func IsSpace(c byte) bool
func IsSpaceRune(r rune) bool
func IsStartOf(s, prefix string) bool
func IsStartsOf(s string, prefixes []string) bool
func IsSymbol(r rune) bool
func IsValidUtf8(s string) bool
func IsVersion(s string) bool
func Join(sep string, ss ...string) string
func JoinList(sep string, ss []string) string
func LTrim(s string, cutSet ...string) string
func Lower(s string) string
func LowerFirst(s string) string
func Lowercase(s string) string
func Ltrim(s string, cutSet ...string) string
func MD5(src interface{}) string
func Md5(src interface{}) string
func MicroTimeHexID() string
func MicroTimeID() string
func MustBool(s string) bool
func MustCut(s, sep string) (before string, after string)
func MustInt(s string) int
func MustInt64(s string) int64
func MustString(in interface{}) string
func MustToTime(s string, layouts ...string) time.Time
func NoCaseEq(s, t string) bool
func PadLeft(s, pad string, length int) string
func PadRight(s, pad string, length int) string
func Padding(s, pad string, length int, pos uint8) string
func PrettyJSON(v interface{}) (string, error)
func QuietBool(s string) bool
func QuietInt(s string) int
func QuietInt64(s string) int64
func QuietString(in interface{}) string
func Quote(s string) string
func RTrim(s string, cutSet ...string) string
func RandomBytes(length int) ([]byte, error)
func RandomChars(ln int) string
func RandomCharsV2(ln int) string
func RandomCharsV3(ln int) string
func RandomString(length int) (string, error)
func RenderTemplate(input string, data interface{}, fns template.FuncMap, isFile ...bool) string
func RenderText(input string, data interface{}, fns template.FuncMap, isFile ...bool) string
func Repeat(s string, times int) string
func RepeatBytes(char byte, times int) (chars []byte)
func RepeatRune(char rune, times int) (chars []rune)
func Replaces(str string, pairs map[string]string) string
func Rtrim(s string, cutSet ...string) string
func RuneCount(s string) int
func RuneIsLower(c rune) bool
func RuneIsUpper(c rune) bool
func RuneIsWord(c rune) bool
func RunePos(s string, ru rune) int
func RuneWidth(r rune) int
func Similarity(s, t string, rate float32) (float32, bool)
func SnakeCase(s string, sep ...string) string
func Split(s, sep string) (ss []string)
func SplitInlineComment(val string) (string, string)
func SplitN(s, sep string, n int) (ss []string)
func SplitNTrimmed(s, sep string, n int) (ss []string)
func SplitNValid(s, sep string, n int) (ss []string)
func SplitTrimmed(s, sep string) (ss []string)
func SplitValid(s, sep string) (ss []string)
func StrPos(s, sub string) int
func String(val interface{}) (string, error)
func StringOrErr(val interface{}) (string, error)
func Strings(s string, sep ...string) []string
func StripSlashes(s string) string
func Substr(s string, pos, length int) string
func TextSplit(s string, w int) []string
func TextTruncate(s string, w int, tail string) string
func TextWidth(s string) int
func TextWrap(s string, w int) string
func Title(s string) string
func ToArray(s string, sep ...string) []string
func ToBool(s string) (bool, error)
func ToBytes(s string) (b []byte)
func ToDuration(s string) (time.Duration, error)
func ToInt(s string) (int, error)
func ToInt64(s string) (int64, error)
func ToIntSlice(s string, sep ...string) (ints []int, err error)
func ToInts(s string, sep ...string) ([]int, error)
func ToSlice(s string, sep ...string) []string
func ToString(val interface{}) (string, error)
func ToStrings(s string, sep ...string) []string
func ToTime(s string, layouts ...string) (t time.Time, err error)
func Trim(s string, cutSet ...string) string
func TrimCut(s, sep string) (string, string)
func TrimLeft(s string, cutSet ...string) string
func TrimRight(s string, cutSet ...string) string
func URLDecode(s string) string
func URLEncode(s string) string
func Unquote(s string) string
func Upper(s string) string
func UpperFirst(s string) string
func UpperWord(s string) string
func Uppercase(s string) string
func Utf8Len(s string) int
func Utf8Split(s string, w int) []string
func Utf8Truncate(s string, w int, tail string) string
func Utf8Width(s string) (size int)
func Utf8len(s string) int
func VersionCompare(v1, v2, op string) bool
func WidthWrap(s string, w int) string
func WrapTag(s, tag string) string

Code Check & Testing

gofmt -w -l ./
golint ./...

Testing:

go test -v ./strutil/...

Test limit by regexp:

go test -v -run ^TestSetByKeys ./strutil/...

Documentation

Overview

Package strutil provide some string,char,byte util functions

Index

Constants

View Source
const (
	Base10Chars = "0123456789"
	Base16Chars = "0123456789abcdef"
	Base32Chars = "0123456789abcdefghjkmnpqrstvwxyz"
	Base36Chars = "0123456789abcdefghijklmnopqrstuvwxyz"
	Base62Chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	Base64Chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/"
)
View Source
const (
	Numbers  = "0123456789"
	HexChars = "0123456789abcdef" // base16

	AlphaBet  = "abcdefghijklmnopqrstuvwxyz"
	AlphaBet1 = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"

	AlphaNum  = "abcdefghijklmnopqrstuvwxyz0123456789"
	AlphaNum2 = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	AlphaNum3 = "0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
)

some consts string chars

Variables

View Source
var (
	// ErrDateLayout error
	ErrDateLayout = errors.New("invalid date layout string")
	// ErrInvalidParam error
	ErrInvalidParam = errors.New("invalid input for parse time")
)
View Source
var (
	B32Std = base32.StdEncoding.WithPadding(base32.NoPadding)
	B32Hex = base32.HexEncoding.WithPadding(base32.NoPadding)
)

base32 encoding with no padding

View Source
var (
	UpWords = UpperWord
	LoFirst = LowerFirst
	UpFirst = UpperFirst

	Snake = SnakeCase
)

methods aliases

View Source
var (
	DefMinInt = 1000
	DefMaxInt = 9999
)

global id:

https://github.com/rs/xid
https://github.com/satori/go.uuid
View Source
var B64Std = base64.StdEncoding.WithPadding(base64.NoPadding)

B64Std base64 encoding with no padding

Equal check, alias of strings.EqualFold

View Source
var ErrInvalidSizeExpr = errors.New("invalid size expr")

ErrInvalidSizeExpr invalid size expression error

View Source
var InArray = HasOneSub

InArray alias of HasOneSub()

View Source
var StartsWith = strings.HasPrefix

StartsWith alias func for HasPrefix

View Source
var StartsWithAny = HasOneSuffix

StartsWithAny alias of the HasOnePrefix

Functions

func AddSlashes added in v0.5.6

func AddSlashes(s string) string

AddSlashes add slashes for the string.

func AfterFirst added in v0.6.12

func AfterFirst(s, sep string) string

AfterFirst get substring after first sep.

func AfterLast added in v0.6.12

func AfterLast(s, sep string) string

AfterLast get substring after last sep.

func AnyToString added in v0.3.10

func AnyToString(val any, defaultAsErr bool) (s string, err error)

AnyToString convert any value to string.

For defaultAsErr:

  • False will use fmt.Sprint convert unsupported type
  • True will return error on convert fail.

func B32Decode added in v0.5.3

func B32Decode(str string) string

B32Decode base32 decode

func B32Encode added in v0.5.3

func B32Encode(str string) string

B32Encode base32 encode

func B64Decode added in v0.5.3

func B64Decode(str string) string

B64Decode base64 decode

func B64DecodeBytes added in v0.6.0

func B64DecodeBytes(str []byte) []byte

B64DecodeBytes base64 decode

func B64Encode added in v0.2.2

func B64Encode(str string) string

B64Encode base64 encode

func B64EncodeBytes added in v0.6.0

func B64EncodeBytes(src []byte) []byte

B64EncodeBytes base64 encode

func Base10Conv added in v0.6.13

func Base10Conv(src string, to int) string

Base10Conv convert base 10 string to new base string.

func BaseConv added in v0.6.13

func BaseConv(src string, from, to int) 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"

func BaseConvByTpl added in v0.6.13

func BaseConvByTpl(src string, fromBase, toBase string) string

BaseConvByTpl convert base string by template.

Usage:

BaseConvert("123", Base62Chars, Base16Chars) // Output: "1e"
BaseConvert("1e", Base16Chars, Base62Chars) // Output: "123"

func BeforeFirst added in v0.6.12

func BeforeFirst(s, sep string) string

BeforeFirst get substring before first sep.

func BeforeLast added in v0.6.12

func BeforeLast(s, sep string) string

BeforeLast get substring before last sep.

func BlankOr added in v0.6.12

func BlankOr(val, defVal string) string

BlankOr return default value on val is blank, otherwise return val

func Bool added in v0.2.2

func Bool(s string) (bool, error)

Bool parse string to bool. like strconv.ParseBool()

func Byte2str added in v0.3.14

func Byte2str(b []byte) string

Byte2str convert bytes to string

func Byte2string added in v0.3.14

func Byte2string(b []byte) string

Byte2string convert bytes to string

func BytePos added in v0.3.12

func BytePos(s string, bt byte) int

BytePos alias of the strings.IndexByte

func Camel added in v0.2.2

func Camel(s string, sep ...string) string

Camel alias of the CamelCase

func CamelCase added in v0.2.2

func CamelCase(s string, sep ...string) string

CamelCase convert string to camel case.

Support:

"range_price" -> "rangePrice"
"range price" -> "rangePrice"
"range-price" -> "rangePrice"

func Compare added in v0.5.10

func Compare(s1, s2, op string) bool

Compare for two string.

func ContainsAll added in v0.6.2

func ContainsAll(s string, subs []string) bool

ContainsAll substr(s) in the given string. alias of HasAllSubs()

func ContainsByte added in v0.6.6

func ContainsByte(s string, c byte) bool

ContainsByte in given string.

func ContainsOne added in v0.6.2

func ContainsOne(s string, subs []string) bool

ContainsOne substr(s) in the given string. alias of HasOneSub()

func Cut added in v0.5.0

func Cut(s, sep string) (before string, after string, found bool)

Cut same of the strings.Cut

func DateSN added in v0.6.13

func DateSN(prefix string) string

DateSN generate date serial number. PREFIX + yyyyMMddHHmmss + ext(微秒+随机数)

func DateSNV2 added in v0.6.13

func DateSNV2(prefix string, extBase ...int) string

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)

func DatetimeNo added in v0.6.9

func DatetimeNo(prefix string) string

DatetimeNo generate. can use for order-no.

  • No prefix, return like: 2023041410484904074285478388(len: 28)
  • With prefix, return like: prefix2023041410484904074285478388(len: 28 + len(prefix))

func EscapeHTML added in v0.2.2

func EscapeHTML(s string) string

EscapeHTML escape html string

func EscapeJS added in v0.2.2

func EscapeJS(s string) string

EscapeJS escape javascript string

func FilterEmail added in v0.2.2

func FilterEmail(s string) string

FilterEmail filter email, clear invalid chars.

func FirstLine added in v0.6.2

func FirstLine(output string) string

FirstLine from command output

func GenMd5

func GenMd5(src any) string

GenMd5 Generate a 32-bit md5 string

func GlobMatch added in v0.6.5

func GlobMatch(pattern, s string) bool

GlobMatch check for a string match the pattern.

Difference with PathMatch() is: `*` can match any char, contain `/`.

func HasAllSubs added in v0.4.0

func HasAllSubs(s string, subs []string) bool

HasAllSubs all substr in the given string.

func HasEmpty added in v0.6.2

func HasEmpty(ss ...string) bool

HasEmpty value for input strings

func HasOnePrefix added in v0.4.0

func HasOnePrefix(s string, prefixes []string) bool

HasOnePrefix the string start withs one of the subs

func HasOneSub added in v0.4.0

func HasOneSub(s string, subs []string) bool

HasOneSub substr(s) in the given string.

func HasOneSuffix added in v0.6.8

func HasOneSuffix(s string, suffixes []string) bool

HasOneSuffix the string end withs one of the subs

func HasPrefix added in v0.3.12

func HasPrefix(s string, prefix string) bool

HasPrefix substr in the given string.

func HasSuffix added in v0.3.12

func HasSuffix(s string, suffix string) bool

HasSuffix substr in the given string.

func HashPasswd added in v0.6.1

func HashPasswd(pwd, key string) string

HashPasswd for quick hash an input password string

func IContains added in v0.6.2

func IContains(s, sub string) bool

IContains ignore case check substr in the given string.

func IEqual added in v0.6.2

func IEqual(s1, s2 string) bool

IEqual ignore case check given two string is equals.

func Implode added in v0.5.0

func Implode(sep string, ss ...string) string

Implode alias of strings.Join

func Indent added in v0.5.9

func Indent(s, prefix string) string

Indent inserts prefix at the beginning of each non-empty line of s. The end-of-line marker is NL.

func IndentBytes added in v0.5.9

func IndentBytes(b, prefix []byte) []byte

IndentBytes inserts prefix at the beginning of each non-empty line of b. The end-of-line marker is NL.

func Int added in v0.2.8

func Int(s string) (int, error)

Int convert string to int, alias of ToInt()

func Int64 added in v0.5.5

func Int64(s string) int64

Int64 convert string to int, will ignore error

func Int64Or added in v0.6.12

func Int64Or(s string, defVal int64) int64

Int64Or convert string to int, return default value on fail

func Int64OrDefault added in v0.6.12

func Int64OrDefault(s string, defVal int64) int64

Int64OrDefault convert string to int, return default value on fail

func Int64OrErr added in v0.5.5

func Int64OrErr(s string) (int64, error)

Int64OrErr convert string to int, return error on fail

func Int64OrPanic added in v0.5.5

func Int64OrPanic(s string) int64

Int64OrPanic convert value to int, will panic on error

func IntOr added in v0.6.12

func IntOr(s string, defVal int) int

IntOr convert string to int, return default value on fail

func IntOrDefault added in v0.6.12

func IntOrDefault(s string, defVal int) int

IntOrDefault convert string to int, return default value on fail

func IntOrPanic added in v0.4.1

func IntOrPanic(s string) int

IntOrPanic convert value to int, will panic on error

func Ints added in v0.3.13

func Ints(s string, sep ...string) []int

Ints alias of the ToIntSlice(). default sep is comma(,)

func IsAllEmpty added in v0.6.2

func IsAllEmpty(ss ...string) bool

IsAllEmpty for input strings

func IsAlphaNum added in v0.3.11

func IsAlphaNum(c uint8) bool

IsAlphaNum reports whether the byte is an ASCII letter, number, or underscore

func IsAlphabet added in v0.2.13

func IsAlphabet(char uint8) bool

IsAlphabet char

func IsBlank added in v0.3.12

func IsBlank(s string) bool

IsBlank returns true if the given string is all space characters.

func IsBlankBytes added in v0.3.12

func IsBlankBytes(bs []byte) bool

IsBlankBytes returns true if the given []byte is all space characters.

func IsEmpty added in v0.4.1

func IsEmpty(s string) bool

IsEmpty returns true if the given string is empty.

func IsEndOf added in v0.3.12

func IsEndOf(s, suffix string) bool

IsEndOf alias of the strings.HasSuffix

func IsNotBlank added in v0.4.1

func IsNotBlank(s string) bool

IsNotBlank returns true if the given string is not blank.

func IsNumChar added in v0.5.8

func IsNumChar(c byte) bool

IsNumChar returns true if the given character is a numeric, otherwise false.

func IsNumeric added in v0.3.12

func IsNumeric(s string) bool

IsNumeric returns true if the given string is a numeric, otherwise false.

func IsSpace added in v0.3.12

func IsSpace(c byte) bool

IsSpace returns true if the given character is a space, otherwise false.

func IsSpaceRune added in v0.3.12

func IsSpaceRune(r rune) bool

IsSpaceRune returns true if the given rune is a space, otherwise false.

func IsStartOf added in v0.3.12

func IsStartOf(s, prefix string) bool

IsStartOf alias of the strings.HasPrefix

func IsStartsOf added in v0.4.0

func IsStartsOf(s string, prefixes []string) bool

IsStartsOf alias of the HasOnePrefix

func IsSymbol added in v0.3.12

func IsSymbol(r rune) bool

IsSymbol reports whether the rune is a symbolic character.

func IsValidUtf8 added in v0.5.6

func IsValidUtf8(s string) bool

IsValidUtf8 valid utf8 string check

func IsVersion added in v0.5.11

func IsVersion(s string) bool

IsVersion number. eg: 1.2.0

func Join added in v0.5.0

func Join(sep string, ss ...string) string

Join alias of strings.Join

func JoinAny added in v0.6.2

func JoinAny(sep string, parts ...any) string

JoinAny type to string

func JoinList added in v0.5.11

func JoinList(sep string, ss []string) string

JoinList alias of strings.Join

func LTrim added in v0.5.0

func LTrim(s string, cutSet ...string) string

LTrim alias of TrimLeft

func LikeMatch added in v0.6.9

func LikeMatch(pattern, s string) bool

LikeMatch simple check for a string match the pattern. pattern like the SQL LIKE.

func Lower added in v0.2.2

func Lower(s string) string

Lower alias of the strings.ToLower()

func LowerFirst

func LowerFirst(s string) string

LowerFirst lower first char

func Lowercase added in v0.2.2

func Lowercase(s string) string

Lowercase alias of the strings.ToLower()

func Ltrim added in v0.3.12

func Ltrim(s string, cutSet ...string) string

Ltrim alias of TrimLeft

func MD5 added in v0.5.6

func MD5(src any) string

MD5 Generate a 32-bit md5 string

func MTimeBaseID added in v0.6.13

func MTimeBaseID(toBase int) string

MTimeBaseID micro time BASE id generate. toBase: 2 - 36

Examples:

  • MTimeBaseID(16): 5b5f0588af1761ad3(len: 16-17)
  • MTimeBaseID(36): gorntzvsa73mo(len: 13)

func MTimeHexID added in v0.6.13

func MTimeHexID() string

MTimeHexID micro time hex id generate.

return like: 5b5f0588af1761ad3(len: 16-17)

func MatchNodePath added in v0.6.8

func MatchNodePath(pattern, s string, sep string) bool

MatchNodePath check for a string match the pattern.

Use on pattern:

  • `*` match any to sep
  • `**` match any to end. only allow at start or end on pattern.

Example:

strutil.MatchNodePath()

func Md5 added in v0.2.2

func Md5(src any) string

Md5 Generate a 32-bit md5 string

func Md5Bytes added in v0.6.0

func Md5Bytes(src any) []byte

Md5Bytes Generate a 32-bit md5 bytes

func MicroTimeHexID added in v0.3.6

func MicroTimeHexID() string

MicroTimeHexID micro time hex id generate.

return like: 5b5f0588af1761ad3(len: 16-17)

func MicroTimeID added in v0.3.6

func MicroTimeID() string

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

func MustBool added in v0.2.2

func MustBool(s string) bool

MustBool convert to bool, will panic on error

func MustCut added in v0.5.0

func MustCut(s, sep string) (before string, after string)

MustCut always returns two substring.

func MustInt added in v0.2.8

func MustInt(s string) int

MustInt convert string to int, will panic on error

func MustInt64 added in v0.5.10

func MustInt64(s string) int64

MustInt64 convert value to int, will panic on error

func MustString added in v0.2.2

func MustString(val any) string

MustString convert value to string, will panic on error

func MustToTime added in v0.5.1

func MustToTime(s string, layouts ...string) time.Time

MustToTime convert date string to time.Time

func MustUint added in v0.6.12

func MustUint(s string) uint64

MustUint convert value to uint, will panic on error. alias of UintOrPanic()

func NewReplacer added in v0.6.7

func NewReplacer(pairs map[string]string) *strings.Replacer

NewReplacer instance

func NoCaseEq added in v0.5.10

func NoCaseEq(s, t string) bool

NoCaseEq check two strings is equals and case-insensitivity

func OrCond added in v0.6.2

func OrCond(cond bool, s1, s2 string) string

OrCond return s1 on cond is True, OR return s2. Like: cond ? s1 : s2

func OrElse added in v0.6.2

func OrElse(s, orVal string) string

OrElse return default value on s is empty, otherwise return s

func OrHandle added in v0.6.2

func OrHandle(s string, fn comdef.StringHandleFunc) string

OrHandle return fn(s) on s is not empty.

func PadBytes added in v0.6.0

func PadBytes(bs []byte, pad byte, length int, pos PosFlag) []byte

PadBytes padding a byte to want length and with position flag

func PadBytesLeft added in v0.6.0

func PadBytesLeft(bs []byte, pad byte, length int) []byte

PadBytesLeft a byte to want length

func PadBytesRight added in v0.6.0

func PadBytesRight(bs []byte, pad byte, length int) []byte

PadBytesRight a byte to want length

func PadChars added in v0.6.0

func PadChars[T byte | rune](cs []T, pad T, length int, pos PosFlag) []T

PadChars padding a rune/byte to want length and with position flag

func PadLeft

func PadLeft(s, pad string, length int) string

PadLeft a string.

func PadRight

func PadRight(s, pad string, length int) string

PadRight a string.

func PadRunes added in v0.6.0

func PadRunes(rs []rune, pad rune, length int, pos PosFlag) []rune

PadRunes padding a rune to want length and with position flag

func PadRunesLeft added in v0.6.0

func PadRunesLeft(rs []rune, pad rune, length int) []rune

PadRunesLeft a rune to want length

func PadRunesRight added in v0.6.0

func PadRunesRight(rs []rune, pad rune, length int) []rune

PadRunesRight a rune to want length

func Padding

func Padding(s, pad string, length int, pos PosFlag) string

Padding a string.

func ParseSizeRange added in v0.6.9

func ParseSizeRange(expr string, opt *ParseSizeOpt) (min, max uint64, err error)

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

func PathMatch added in v0.6.8

func PathMatch(pattern, s string) bool

PathMatch check for a string match the pattern. alias of the path.Match()

TIP: `*` can match any char, not contain `/`.

func QuickMatch added in v0.6.5

func QuickMatch(pattern, s string) bool

QuickMatch check for a string. pattern can be a sub string.

func QuietBool added in v0.5.3

func QuietBool(s string) bool

QuietBool convert to bool, will ignore error

func QuietCut added in v0.6.2

func QuietCut(s, sep string) (before string, after string)

QuietCut always returns two substring.

func QuietInt added in v0.5.5

func QuietInt(s string) int

QuietInt convert string to int, will ignore error

func QuietInt64 added in v0.5.5

func QuietInt64(s string) int64

QuietInt64 convert string to int, will ignore error

func QuietString added in v0.5.3

func QuietString(val any) string

QuietString convert value to string, will ignore error. same as SafeString()

func Quote added in v0.5.9

func Quote(s string) string

Quote alias of strings.Quote

func RTrim added in v0.5.0

func RTrim(s string, cutSet ...string) string

RTrim alias of TrimRight

func RandWithTpl added in v0.6.9

func RandWithTpl(n int, letters string) string

RandWithTpl generate random string with give template

func RandomBytes

func RandomBytes(length int) ([]byte, error)

RandomBytes generate

func RandomChars added in v0.3.6

func RandomChars(ln int) string

RandomChars generate give length random chars at `a-z`

func RandomCharsV2 added in v0.3.6

func RandomCharsV2(ln int) string

RandomCharsV2 generate give length random chars in `0-9a-z`

func RandomCharsV3 added in v0.3.6

func RandomCharsV3(ln int) string

RandomCharsV3 generate give length random chars in `0-9a-zA-Z`

func RandomString

func RandomString(length int) (string, error)

RandomString generate.

Example:

// this will give us a 44 byte, base64 encoded output
token, err := RandomString(16) // eg: "I7S4yFZddRMxQoudLZZ-eg"

func Repeat

func Repeat(s string, times int) string

Repeat a string by given times.

func RepeatBytes added in v0.3.10

func RepeatBytes(char byte, times int) []byte

RepeatBytes repeat a byte char.

func RepeatChars added in v0.6.0

func RepeatChars[T byte | rune](char T, times int) []T

RepeatChars repeat a byte char.

func RepeatRune

func RepeatRune(char rune, times int) []rune

RepeatRune repeat a rune char.

func Replaces

func Replaces(str string, pairs map[string]string) string

Replaces replace multi strings

pairs: {old1: new1, old2: new2, ...}

Can also use:

strings.NewReplacer("old1", "new1", "old2", "new2").Replace(str)

func Resize added in v0.6.0

func Resize(s string, length int, align PosFlag) string

Resize a string by given length and align settings. padding space.

func Rtrim added in v0.3.12

func Rtrim(s string, cutSet ...string) string

Rtrim alias of TrimRight

func RuneCount added in v0.5.8

func RuneCount(s string) int

RuneCount of the string

func RuneIsLower added in v0.5.9

func RuneIsLower(c rune) bool

RuneIsLower char

func RuneIsUpper added in v0.5.9

func RuneIsUpper(c rune) bool

RuneIsUpper char

func RuneIsWord added in v0.5.9

func RuneIsWord(c rune) bool

RuneIsWord char: a-zA-Z

func RunePos added in v0.3.12

func RunePos(s string, ru rune) int

RunePos alias of the strings.IndexRune

func RuneWidth added in v0.5.8

func RuneWidth(r rune) int

RuneWidth of the rune.

Example:

RuneWidth('你') // 2
RuneWidth('a') // 1
RuneWidth('\n') // 0

func RunesWidth added in v0.6.0

func RunesWidth(rs []rune) (w int)

RunesWidth utf8 runes string width.

Examples:

str := "hi,你好"

len(str) // 9
strutil.Utf8Width(str) // 7
len([]rune(str)) = utf8.RuneCountInString(s) // 5

func SafeBool added in v0.6.12

func SafeBool(s string) bool

SafeBool convert to bool, will ignore error

func SafeByteSize added in v0.6.9

func SafeByteSize(sizeStr string) uint64

SafeByteSize converts size string like 1GB/1g or 12mb/12M into an unsigned integer number of bytes

func SafeInt added in v0.6.12

func SafeInt(s string) int

SafeInt convert string to int, will ignore error

func SafeInt64 added in v0.6.12

func SafeInt64(s string) int64

SafeInt64 convert string to int, will ignore error

func SafeString added in v0.6.5

func SafeString(in any) string

SafeString convert value to string, will ignore error

func SafeUint added in v0.6.12

func SafeUint(s string) uint64

SafeUint convert string to uint, will ignore error

func ShortMd5 added in v0.6.13

func ShortMd5(src any) string

ShortMd5 Generate a 16-bit md5 string. remove first 8 and last 8 bytes from 32-bit md5 string.

func Similarity

func Similarity(s, t string, rate float32) (float32, bool)

Similarity calc for two string.

Usage:

rate, ok := Similarity("hello", "he")

func SimpleMatch added in v0.6.9

func SimpleMatch(s string, keywords []string) bool

SimpleMatch all sub-string in the give text string.

Difference the ContainsAll:

  • start with ^ for exclude contains check.
  • end with $ for check end with keyword.

func SnakeCase added in v0.2.2

func SnakeCase(s string, sep ...string) string

SnakeCase convert. eg "RangePrice" -> "range_price"

func Split

func Split(s, sep string) (ss []string)

Split string to slice. will trim each item and filter empty string node.

func SplitInlineComment added in v0.5.14

func SplitInlineComment(val string, strict ...bool) (string, string)

SplitInlineComment for an inline text string.

func SplitKV added in v0.6.6

func SplitKV(s, sep string) (string, string)

SplitKV split string to key and value.

func SplitN added in v0.4.0

func SplitN(s, sep string, n int) (ss []string)

SplitN string to slice. will filter empty string node.

func SplitNTrimmed added in v0.4.0

func SplitNTrimmed(s, sep string, n int) (ss []string)

SplitNTrimmed split string to slice. will trim space for each node, but not filter empty

func SplitNValid added in v0.4.0

func SplitNValid(s, sep string, n int) (ss []string)

SplitNValid string to slice. will filter empty string node.

func SplitTrimmed added in v0.4.0

func SplitTrimmed(s, sep string) (ss []string)

SplitTrimmed split string to slice. will trim space for each node, but not filter empty

func SplitValid added in v0.4.0

func SplitValid(s, sep string) (ss []string)

SplitValid string to slice. will trim each item and filter empty string node.

func StrPos added in v0.3.12

func StrPos(s, sub string) int

StrPos alias of the strings.Index

func String added in v0.2.2

func String(val any) (string, error)

String convert value to string, return error on failed

func StringOr added in v0.6.12

func StringOr(val any, defVal string) string

StringOr convert any value to string, return default value on failed

func StringOrDefault added in v0.6.12

func StringOrDefault(val any, defVal string) string

StringOrDefault convert any value to string, return default value on failed

func StringOrErr added in v0.5.3

func StringOrErr(val any) (string, error)

StringOrErr convert value to string, return error on failed

func StringOrPanic added in v0.6.12

func StringOrPanic(val any) string

StringOrPanic convert value to string, will panic on error

func Strings added in v0.3.13

func Strings(s string, sep ...string) []string

Strings alias of the ToSlice()

func StripSlashes added in v0.5.6

func StripSlashes(s string) string

StripSlashes strip slashes for the string.

func Substr

func Substr(s string, pos, length int) string

Substr for a string. if length <= 0, return pos to end.

func SubstrCount added in v0.6.1

func SubstrCount(s, substr string, params ...uint64) (int, error)

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.

func TextSplit added in v0.5.8

func TextSplit(s string, w int) []string

TextSplit alias of the Utf8Split()

func TextTruncate added in v0.5.8

func TextTruncate(s string, w int, tail string) string

TextTruncate alias of the Utf8Truncate()

func TextWidth added in v0.5.8

func TextWidth(s string) int

TextWidth utf8 string width. alias of RunesWidth()

func TextWrap added in v0.5.8

func TextWrap(s string, w int) string

TextWrap a string by "\n"

func Title added in v0.2.2

func Title(s string) string

Title alias of the strings.ToTitle()

func ToArray added in v0.2.2

func ToArray(s string, sep ...string) []string

ToArray alias of the ToSlice()

func ToBool added in v0.2.2

func ToBool(s string) (bool, error)

ToBool convert string to bool

func ToByteSize added in v0.6.9

func ToByteSize(sizeStr string) (uint64, error)

ToByteSize converts size string like 1GB/1g or 12mb/12M into an unsigned integer number of bytes

func ToBytes added in v0.3.14

func ToBytes(s string) (b []byte)

ToBytes convert string to bytes

func ToDuration added in v0.5.6

func ToDuration(s string) (time.Duration, error)

ToDuration parses a duration string. such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".

func ToInt added in v0.2.8

func ToInt(s string) (int, error)

ToInt convert string to int, return error on fail

func ToInt64 added in v0.5.10

func ToInt64(s string) (int64, error)

ToInt64 convert string to int, return error on fail

func ToIntSlice added in v0.2.2

func ToIntSlice(s string, sep ...string) (ints []int, err error)

ToIntSlice split string to slice and convert item to int.

Default sep is comma

func ToInts added in v0.2.2

func ToInts(s string, sep ...string) ([]int, error)

ToInts alias of the ToIntSlice(). default sep is comma(,)

func ToSlice added in v0.2.2

func ToSlice(s string, sep ...string) []string

ToSlice split string to array.

func ToString added in v0.2.2

func ToString(val any) (string, error)

ToString convert value to string, return error on failed

func ToStringWith added in v0.6.15

func ToStringWith(in any, optFns ...comfunc.ConvOptionFn) (string, error)

ToStringWith try to convert value to string. can with some option func, more see comfunc.ConvOption.

func ToStrings added in v0.3.13

func ToStrings(s string, sep ...string) []string

ToStrings alias of the ToSlice()

func ToTime added in v0.2.2

func ToTime(s string, layouts ...string) (t time.Time, err error)

ToTime convert date string to time.Time

func ToUint added in v0.6.12

func ToUint(s string) (uint64, error)

ToUint convert string to uint, return error on fail. alias of UintOrErr()

func Trim added in v0.2.2

func Trim(s string, cutSet ...string) string

Trim string. if cutSet is empty, will trim SPACE.

func TrimCut added in v0.5.8

func TrimCut(s, sep string) (string, string)

TrimCut always returns two substring and trim space for items.

func TrimLeft added in v0.2.2

func TrimLeft(s string, cutSet ...string) string

TrimLeft char in the string. if cutSet is empty, will trim SPACE.

func TrimRight added in v0.2.2

func TrimRight(s string, cutSet ...string) string

TrimRight char in the string. if cutSet is empty, will trim SPACE.

func Truncate added in v0.6.8

func Truncate(s string, w int, tail string) string

Truncate alias of the Utf8Truncate()

func URLDecode added in v0.2.2

func URLDecode(s string) string

URLDecode decode url string.

func URLEncode added in v0.2.2

func URLEncode(s string) string

URLEncode encode url string.

func Uint added in v0.6.12

func Uint(s string) uint64

Uint convert string to uint, will ignore error

func UintOr added in v0.6.12

func UintOr(s string, defVal uint64) uint64

UintOr convert string to uint, return default value on fail

func UintOrDefault added in v0.6.12

func UintOrDefault(s string, defVal uint64) uint64

UintOrDefault convert string to uint, return default value on fail

func UintOrErr added in v0.6.12

func UintOrErr(s string) (uint64, error)

UintOrErr convert string to uint, return error on fail

func UintOrPanic added in v0.6.12

func UintOrPanic(s string) uint64

UintOrPanic convert value to uint, will panic on error

func Unquote added in v0.5.9

func Unquote(s string) string

Unquote remove start and end quotes by single-quote or double-quote

tip: strconv.Unquote cannot unquote single-quote

func Upper added in v0.2.2

func Upper(s string) string

Upper alias of the strings.ToUpper()

func UpperFirst

func UpperFirst(s string) string

UpperFirst upper first char

func UpperWord

func UpperWord(s string) string

UpperWord Change the first character of each word to uppercase

func Uppercase added in v0.2.2

func Uppercase(s string) string

Uppercase alias of the strings.ToUpper()

func Utf8Len added in v0.5.6

func Utf8Len(s string) int

Utf8Len count of the string

func Utf8Split added in v0.5.8

func Utf8Split(s string, w int) []string

Utf8Split split a string by width.

func Utf8Truncate added in v0.5.8

func Utf8Truncate(s string, w int, tail string) string

Utf8Truncate a string with given width.

func Utf8Width added in v0.5.8

func Utf8Width(s string) int

Utf8Width utf8 string width. alias of RunesWidth

func Utf8len added in v0.3.12

func Utf8len(s string) int

Utf8len of the string

func Valid added in v0.6.2

func Valid(ss ...string) string

Valid return first not empty element.

func VerifyPasswd added in v0.6.1

func VerifyPasswd(pwdMAC, pwd, key string) bool

VerifyPasswd for quick verify input password is valid

- pwdMAC from db or config, generated by EncryptPasswd()

func VersionCompare added in v0.5.5

func VersionCompare(v1, v2, op string) bool

VersionCompare for two version string.

func WidthWrap added in v0.5.8

func WidthWrap(s string, w int) string

WidthWrap a string by "\n"

func WordWrap added in v0.6.0

func WordWrap(s string, w int) string

WordWrap text string and limit width.

func WrapTag added in v0.5.8

func WrapTag(s, tag string) string

WrapTag for given string.

func ZeroOr added in v0.6.12

func ZeroOr[T ~string](val, defVal T) T

ZeroOr return default value on val is zero, otherwise return val. same of OrElse()

Types

type Buffer added in v0.5.3

type Buffer = byteutil.Buffer

Buffer wrap and extends the bytes.Buffer

func NewBuffer added in v0.5.10

func NewBuffer() *Buffer

NewBuffer instance

type Builder added in v0.6.5

type Builder struct {
	strings.Builder
}

Builder struct

func (*Builder) ResetGet added in v0.6.11

func (b *Builder) ResetGet() string

ResetGet return current string and reset builder

func (*Builder) Write added in v0.6.5

func (b *Builder) Write(p []byte)

Write bytes and no error report

func (*Builder) WriteAny added in v0.6.5

func (b *Builder) WriteAny(v any)

WriteAny write any type value.

func (*Builder) WriteAnys added in v0.6.5

func (b *Builder) WriteAnys(vs ...any)

WriteAnys write any type values.

func (*Builder) WriteByteNE added in v0.6.5

func (b *Builder) WriteByteNE(c byte)

WriteByteNE write byte and no error report

func (*Builder) WriteMulti added in v0.6.5

func (b *Builder) WriteMulti(bs ...byte)

WriteMulti write multi byte at once.

func (*Builder) WriteRune added in v0.6.5

func (b *Builder) WriteRune(r rune)

WriteRune and no error report

func (*Builder) WriteString added in v0.6.5

func (b *Builder) WriteString(s string)

WriteString to builder

func (*Builder) WriteStrings added in v0.6.5

func (b *Builder) WriteStrings(ss ...string)

WriteStrings write multi string at once.

func (*Builder) Writef added in v0.6.5

func (b *Builder) Writef(tpl string, vs ...any)

Writef write string by fmt.Sprintf formatted

func (*Builder) Writeln added in v0.6.5

func (b *Builder) Writeln(s string)

Writeln write string with newline.

type ByteChanPool added in v0.4.0

type ByteChanPool = byteutil.ChanPool

ByteChanPool struct

Usage:

bp := strutil.NewByteChanPool(500, 1024, 1024)
buf:=bp.Get()
defer bp.Put(buf)
// use buf do something ...

func NewByteChanPool added in v0.4.0

func NewByteChanPool(maxSize, width, capWidth int) *ByteChanPool

NewByteChanPool instance

type ParseSizeOpt added in v0.6.9

type ParseSizeOpt struct {
	// OneAsMax if only one size value, use it as max size. default is false
	OneAsMax bool
	// SepChar is the separator char for time range string. default is '~'
	SepChar byte
	// KeywordFn is the function for parse keyword time string.
	KeywordFn func(string) (min, max uint64, err error)
}

ParseSizeOpt parse size expression options

type PosFlag added in v0.6.0

type PosFlag uint8

PosFlag type

const (
	PosLeft PosFlag = iota
	PosRight
	PosMiddle
)

Position for padding/resize string

type Runes added in v0.6.0

type Runes []rune

Runes data slice

func (Runes) PadLeft added in v0.6.0

func (rs Runes) PadLeft(pad rune, length int) []rune

PadLeft a rune to want length

func (Runes) PadRight added in v0.6.0

func (rs Runes) PadRight(pad rune, length int) []rune

PadRight a rune to want length

func (Runes) Padding added in v0.6.0

func (rs Runes) Padding(pad rune, length int, pos PosFlag) []rune

Padding a rune to want length and with position

type SimilarComparator

type SimilarComparator struct {
	// contains filtered or unexported fields
}

SimilarComparator definition

links:

https://github.com/mkideal/cli/blob/master/fuzzy.go

func NewComparator

func NewComparator(src, dst string) *SimilarComparator

NewComparator create

func (*SimilarComparator) Similar

func (c *SimilarComparator) Similar(minDifferRate float32) (float32, bool)

Similar by minDifferRate

Usage:

c := NewComparator("hello", "he")
rate, ok :c.Similar(0.3)

type StrVal added in v0.5.3

type StrVal = Value

StrVal string. alias of Value

type Value added in v0.5.5

type Value string

Value string

func (Value) Bool added in v0.5.5

func (s Value) Bool() bool

Bool convert

func (Value) Bytes added in v0.5.5

func (s Value) Bytes() []byte

Bytes string to bytes

func (Value) HasPrefix added in v0.5.5

func (s Value) HasPrefix(sub string) bool

HasPrefix prefix

func (Value) HasSuffix added in v0.5.5

func (s Value) HasSuffix(sub string) bool

HasSuffix suffix

func (Value) Int added in v0.5.5

func (s Value) Int() int

Int convert

func (Value) Int64 added in v0.5.5

func (s Value) Int64() int64

Int64 convert

func (Value) IsBlank added in v0.6.2

func (s Value) IsBlank() bool

IsBlank check

func (Value) IsEmpty added in v0.5.5

func (s Value) IsEmpty() bool

IsEmpty check

func (Value) IsEndWith added in v0.5.5

func (s Value) IsEndWith(sub string) bool

IsEndWith suffix

func (Value) IsStartWith added in v0.5.5

func (s Value) IsStartWith(sub string) bool

IsStartWith prefix

func (Value) OrElse added in v0.6.2

func (s Value) OrElse(or string) string

OrElse string

func (*Value) Set added in v0.5.5

func (s *Value) Set(val string) error

Set value

func (Value) Split added in v0.5.5

func (s Value) Split(sep string) []string

Split string

func (Value) SplitN added in v0.5.5

func (s Value) SplitN(sep string, n int) []string

SplitN string

func (Value) String added in v0.5.5

func (s Value) String() string

Value string

func (Value) Val added in v0.5.5

func (s Value) Val() string

Val string

func (Value) WithTrimSpace added in v0.6.2

func (s Value) WithTrimSpace() Value

WithTrimSpace string and return new

Directories

Path Synopsis
Package textscan Implemented a parser that quickly scans and analyzes text content.
Package textscan Implemented a parser that quickly scans and analyzes text content.
Package textutil provide some extensions text handle util functions.
Package textutil provide some extensions text handle util functions.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL