Skip to content

Import path: gitlab.soludian.com/soludian/fountain/libs/base/string_util

string_util

go
import "gitlab.soludian.com/soludian/fountain/libs/base/string_util"

Match provides a simple pattern matcher with unicode support.

Package string_util provide some string,char,byte util functions

Index

Constants

some consts string chars

go
const (
    KNumbers  = "0123456789"
    KHexChars = "0123456789abcdef"

    KAlphaBet  = "abcdefghijklmnopqrstuvwxyz"
    KAlphaBet1 = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"

    KAlphaNum  = "abcdefghijklmnopqrstuvwxyz0123456789"
    KAlphaNum2 = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    KAlphaNum3 = "0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"

    KBase62Chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    KBase64Chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/"
)

Variables

go
var (
    // ErrDateLayout error
    ErrDateLayout = errors.New("invalid date layout string")
    // ErrInvalidParam error
    ErrInvalidParam = errors.New("invalid input for parse time")
)

methods aliases

go
var (
    UpWords = UpperWord
    LoFirst = LowerFirst
    UpFirst = UpperFirst

    Snake = SnakeCase
)

global id:

https://github.com/rs/xid
https://github.com/satori/go.uuid
go
var (
    DefMinInt = 1000
    DefMaxInt = 9999
)

Equal check, alias of strings.EqualFold

go
var Equal = strings.EqualFold

ErrInvalidSizeExpr invalid size expression error

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

SprintToStrFunc convert any value to string by fmt.Sprint

go
var SprintToStrFunc = func(v any) (string, error) {
    if v == nil {
        return "", nil
    }
    return fmt.Sprint(v), nil
}

func AddIrregularRule

go
func AddIrregularRule(single string, plural string)

AddIrregularRule -- Add an irregular word definition.

func AddPluralRule

go
func AddPluralRule(rule string, replacement string)

AddPluralRule -- Add a pluralization rule to the collection.

func AddSingularRule

go
func AddSingularRule(rule string, replacement string)

AddSingularRule -- Add a singularization rule to the collection.

func AddSlashes

go
func AddSlashes(s string) string

AddSlashes add slashes for the string.

func AddUncountableRule

go
func AddUncountableRule(word string)

AddUncountableRule -- Add an uncountable word rule.

func AfterFirst

go
func AfterFirst(s, sep string) string

AfterFirst get substring after first sep.

func AfterLast

go
func AfterLast(s, sep string) string

AfterLast get substring after last sep.

func Allowable

go
func Allowable(pattern string) (min, max string)

Allowable parses the pattern and determines the minimum and maximum allowable values that the pattern can represent. When the max cannot be determined, 'true' will be returned for infinite.

func AnyToString

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

AnyToString convert any value to string.

For defaultAsErr:

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

func B32HexDecode

go
func B32HexDecode(str string) string

B32HexDecode base32 decode

func B32HexEncode

go
func B32HexEncode(str string) string

B32HexEncode base32 encode

func B32StdDecode

go
func B32StdDecode(str string) string

B32StdDecode base32 std decode

func B32StdEncode

go
func B32StdEncode(str string) string

B32StdEncode base32 std encode

func B64RawURLDecode

go
func B64RawURLDecode(str string) string

B64Decode base64 raw url decode

func B64RawURLDecodeBytes

go
func B64RawURLDecodeBytes(str string) []byte

B64RawURLDecodeBytes base64 raw url decode

func B64RawURLEncode

go
func B64RawURLEncode(str string) string

B64RawURLEncode base64 raw url encode

func B64RawURLEncodeBytes

go
func B64RawURLEncodeBytes(src []byte) string

B64RawURLEncodeBytes base64 raw url encode

func B64StdDecode

go
func B64StdDecode(str string) string

B64StdDecode base64 std decode

func B64StdDecodeBytes

go
func B64StdDecodeBytes(str string) []byte

B64StdDecodeBytes base64 std decode

func B64StdEncode

go
func B64StdEncode(str string) string

B64StdEncode base64 std encode

func B64StdEncodeBytes

go
func B64StdEncodeBytes(src []byte) string

B64StdEncodeBytes base64 std encode

func B64URLDecode

go
func B64URLDecode(str string) string

B64Decode base64 url decode

func B64URLDecodeBytes

go
func B64URLDecodeBytes(str string) []byte

B64URLDecodeBytes base64 url decode

func B64URLEncode

go
func B64URLEncode(str string) string

B64URLEncode base64 url encode

func B64URLEncodeBytes

go
func B64URLEncodeBytes(src []byte) string

B64URLEncodeBytes base64 url encode

func BeforeFirst

go
func BeforeFirst(s, sep string) string

BeforeFirst get substring before first sep.

func BeforeLast

go
func BeforeLast(s, sep string) string

BeforeLast get substring before last sep.

func BlankOr

go
func BlankOr(val, defVal string) string

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

func Bool

go
func Bool(s string) (bool, error)

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

func Byte2str

go
func Byte2str(b []byte) string

Byte2str converts a byte slice to a string without copy.

func Byte2string

go
func Byte2string(b []byte) string

Byte2string converts a byte slice to a string without copy.

func BytePos

go
func BytePos(s string, bt byte) int

BytePos alias of the strings.IndexByte

func Camel

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

Camel alias of the CamelCase

func CamelCase

go
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

go
func Compare(s1, s2, op string) bool

Compare for two string.

func ContainsAll

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

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

func ContainsByte

go
func ContainsByte(s string, c byte) bool

ContainsByte in given string.

func ContainsOne

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

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

func Cut

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

Cut same of the strings.Cut

func DatetimeNo

go
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

go
func EscapeHTML(s string) string

EscapeHTML escape html string

func EscapeJS

go
func EscapeJS(s string) string

EscapeJS escape javascript string

func FilterEmail

go
func FilterEmail(s string) string

FilterEmail filter email, clear invalid chars.

func FirstLine

go
func FirstLine(output string) string

FirstLine from command output

func Float32

go
func Float32(s string) float32

Float64 convert string to float32, will ignore error

func Float32Or

go
func Float32Or(s string, defVal float32) float32

Float32Or convert string to float32, return default value on fail

func Float32OrDefault

go
func Float32OrDefault(s string, defVal float32) float32

Float32OrDefault convert string to float32, return default value on fail

func Float32OrErr

go
func Float32OrErr(s string) (float32, error)

Float32OrErr convert string to float32, return error on fail

func Float32OrPanic

go
func Float32OrPanic(s string) float32

Float32OrPanic convert value to float32, will panic on error

func Float64

go
func Float64(s string) float64

Float64 convert string to float64, will ignore error

func Float64Or

go
func Float64Or(s string, defVal float64) float64

Float64Or convert string to float64, return default value on fail

func Float64OrDefault

go
func Float64OrDefault(s string, defVal float64) float64

Float64OrDefault convert string to float64, return default value on fail

func Float64OrErr

go
func Float64OrErr(s string) (float64, error)

Float64OrErr convert string to float64, return error on fail

func Float64OrPanic

go
func Float64OrPanic(s string) float64

Float64OrPanic convert value to float64, will panic on error

func FromBytes

go
func FromBytes(b []byte) string

FromBytes converts a byte slice to a string without copy.

func GlobMatch

go
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

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

HasAllSubs all substr in the given string.

func HasEmpty

go
func HasEmpty(ss ...string) bool

HasEmpty value for input strings

func HasOnePrefix

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

HasOnePrefix the string start withs one of the subs

func HasOneSub

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

HasOneSub substr(s) in the given string.

func HasOneSuffix

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

HasOneSuffix the string end withs one of the subs

func HasPrefix

go
func HasPrefix(s string, prefix string) bool

HasPrefix substr in the given string.

func HasSuffix

go
func HasSuffix(s string, suffix string) bool

HasSuffix substr in the given string.

func IContains

go
func IContains(s, sub string) bool

IContains ignore case check substr in the given string.

func IEqual

go
func IEqual(s1, s2 string) bool

IEqual ignore case check given two string is equals.

func Implode

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

Implode alias of strings.Join

func Indent

go
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

go
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

go
func Int(s string) (int, error)

Int convert string to int, alias of ToInt()

func Int32

go
func Int32(s string) (int32, error)

Int32 convert string to int32, alias of ToInt32()

func Int32Or

go
func Int32Or(s string, defVal int32) int32

Int32Or convert string to int32, return default value on fail

func Int32OrDefault

go
func Int32OrDefault(s string, defVal int32) int32

Int32OrDefault convert string to int32, return default value on fail

func Int32OrPanic

go
func Int32OrPanic(s string) int32

Int32OrPanic convert value to int32, will panic on error

func Int64

go
func Int64(s string) int64

Int64 convert string to int, will ignore error

func Int64Or

go
func Int64Or(s string, defVal int64) int64

Int64Or convert string to int, return default value on fail

func Int64OrDefault

go
func Int64OrDefault(s string, defVal int64) int64

Int64OrDefault convert string to int, return default value on fail

func Int64OrErr

go
func Int64OrErr(s string) (int64, error)

Int64OrErr convert string to int, return error on fail

func Int64OrPanic

go
func Int64OrPanic(s string) int64

Int64OrPanic convert value to int, will panic on error

func IntOr

go
func IntOr(s string, defVal int) int

IntOr convert string to int, return default value on fail

func IntOrDefault

go
func IntOrDefault(s string, defVal int) int

IntOrDefault convert string to int, return default value on fail

func IntOrPanic

go
func IntOrPanic(s string) int

IntOrPanic convert value to int, will panic on error

func Ints

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

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

func IsAllEmpty

go
func IsAllEmpty(ss ...string) bool

IsAllEmpty for input strings

func IsAlphaNum

go
func IsAlphaNum(c uint8) bool

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

func IsAlphabet

go
func IsAlphabet(char uint8) bool

IsAlphabet char

func IsBlank

go
func IsBlank(s string) bool

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

func IsBlankBytes

go
func IsBlankBytes(bs []byte) bool

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

func IsEmpty

go
func IsEmpty(s string) bool

IsEmpty returns true if the given string is empty.

func IsEndOf

go
func IsEndOf(s, suffix string) bool

IsEndOf alias of the strings.HasSuffix

func IsNotBlank

go
func IsNotBlank(s string) bool

IsNotBlank returns true if the given string is not blank.

func IsNumChar

go
func IsNumChar(c byte) bool

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

func IsNumeric

go
func IsNumeric(s string) bool

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

func IsPlural

go
func IsPlural(word string) bool

IsPlural -- Check if a word is plural.

func IsSingular

go
func IsSingular(word string) bool

IsSingular -- Check if a word is singular.

func IsSpace

go
func IsSpace(c byte) bool

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

func IsSpaceRune

go
func IsSpaceRune(r rune) bool

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

func IsStartOf

go
func IsStartOf(s, prefix string) bool

IsStartOf alias of the strings.HasPrefix

func IsStartsOf

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

IsStartsOf alias of the HasOnePrefix

func IsSymbol

go
func IsSymbol(r rune) bool

IsSymbol reports whether the rune is a symbolic character.

func IsValidUtf8

go
func IsValidUtf8(s string) bool

IsValidUtf8 valid utf8 string check

func IsVersion

go
func IsVersion(s string) bool

IsVersion number. eg: 1.2.0

func Join

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

Join alias of strings.Join

func JoinAny

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

JoinAny type to string

func JoinList

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

JoinList alias of strings.Join

func LTrim

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

LTrim alias of TrimLeft

func LikeMatch

go
func LikeMatch(pattern, s string) bool

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

func Lower

go
func Lower(s string) string

Lower alias of the strings.ToLower()

func LowerFirst

go
func LowerFirst(s string) string

LowerFirst lower first char

func Lowercase

go
func Lowercase(s string) string

Lowercase alias of the strings.ToLower()

func Ltrim

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

Ltrim alias of TrimLeft

func MatchNodePath

go
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:

string_util.MatchNodePath()

func MaybeWildcard

go
func MaybeWildcard(str string) bool

Match returns true if the pattern matches the s string. The pattern can contain the wildcard characters '?' and '*'.

func MicroTimeHexID

go
func MicroTimeHexID() string

MicroTimeHexID generate. return like: 5b5f0588af1761ad3(len: 16-17)

func MicroTimeID

go
func MicroTimeID() string

MicroTimeID generate. return like: 16074145697981929446(len: 20)

func MustBool

go
func MustBool(s string) bool

MustBool convert to bool, will panic on error

func MustCut

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

MustCut always returns two substring.

func MustFloat32

go
func MustFloat32(s string) float32

MustFloat32 convert value to float32, will panic on error

func MustFloat64

go
func MustFloat64(s string) float64

MustFloat64 convert value to float64, will panic on error

func MustInt

go
func MustInt(s string) int

MustInt convert string to int, will panic on error

func MustInt32

go
func MustInt32(s string) int32

MustInt32 convert string to int32, will panic on error

func MustInt64

go
func MustInt64(s string) int64

MustInt64 convert value to int, will panic on error

func MustString

go
func MustString(val any) string

MustString convert value to string, will panic on error

func MustToTime

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

MustToTime convert date string to time.Time

func MustUint

go
func MustUint(s string) uint64

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

func NewReplacer

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

NewReplacer instance

func NewShortUUID

go
func NewShortUUID() string

NewShortUUID returns a new short UUID (22 chars).

func NewULID

go
func NewULID() string

NewULID returns a new ULID (26 chars).

func NewUUID

go
func NewUUID() string

NewUUID returns a new UUID Version 4 (36 chars).

func NoCaseEq

go
func NoCaseEq(s, t string) bool

NoCaseEq check two strings is equals and case-insensitivity

func OrCond

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

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

func OrElse

go
func OrElse(s, orVal string) string

OrElse return default value on val is zero, else return s

func OrHandle

go
func OrHandle(s string, fn com_def.StringHandleFunc) string

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

func PadBytes

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

PadBytes padding a byte to want length and with position flag

func PadBytesLeft

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

PadBytesLeft a byte to want length

func PadBytesRight

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

PadBytesRight a byte to want length

func PadChars

go
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

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

PadLeft a string.

func PadRight

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

PadRight a string.

func PadRunes

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

PadRunes padding a rune to want length and with position flag

func PadRunesLeft

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

PadRunesLeft a rune to want length

func PadRunesRight

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

PadRunesRight a rune to want length

func Padding

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

Padding a string.

func ParseSizeRange

go
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

go
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 Plural

go
func Plural(word string) string

Plural -- Pluralize a word.

func Pluralize

go
func Pluralize(word string, count int, inclusive bool) string

Pluralize -- Pluralize or singularize a word based on the passed in count.

word: the word to pluralize
count: how many of the word exist
inclusive: whether to prefix with the number (e.g. 3 ducks)

func QuickMatch

go
func QuickMatch(pattern, s string) bool

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

func QuietBool

go
func QuietBool(s string) bool

QuietBool convert to bool, will ignore error

func QuietCut

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

QuietCut always returns two substring.

func QuietFloat32

go
func QuietFloat32(s string) float32

QuietFloat64 convert string to float32, will ignore error

func QuietFloat64

go
func QuietFloat64(s string) float64

QuietFloat64 convert string to float64, will ignore error

func QuietInt

go
func QuietInt(s string) int

QuietInt convert string to int, will ignore error

func QuietInt32

go
func QuietInt32(s string) int32

QuietInt32 convert string to int32, will ignore error

func QuietInt64

go
func QuietInt64(s string) int64

QuietInt64 convert string to int, will ignore error

func QuietString

go
func QuietString(val any) string

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

func Quote

go
func Quote(s string) string

Quote alias of strings.Quote

func RTrim

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

RTrim alias of TrimRight

func RandWithTpl

go
func RandWithTpl(n int, letters string) string

RandWithTpl generate random string with give template

func RandomBytes

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

RandomBytes generate

func RandomChars

go
func RandomChars(ln int) string

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

func RandomCharsV2

go
func RandomCharsV2(ln int) string

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

func RandomCharsV3

go
func RandomCharsV3(ln int) string

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

func RandomString

go
func RandomString(length int) (string, error)

RandomString generate.

Example:

// this will give us a 44 byte, base64 encoded output
	token, err := RandomString(32)
	if err != nil {
    // Serve an appropriately vague error to the
    // user, but log the details internally.
	}

func RemoveDiacritics

go
func RemoveDiacritics(s string) string

func RenderTemplate

go
func RenderTemplate(input string, data any, fns template.FuncMap, isFile ...bool) string

RenderTemplate quickly render text template.

Deprecated: please use text_util.RenderTpl() instead it

func RenderText

go
func RenderText(input string, data any, fns template.FuncMap, isFile ...bool) string

RenderText quickly render text template

Deprecated: please use text_util.RenderTpl() instead it

func Repeat

go
func Repeat(s string, times int) string

Repeat a string by given times.

func RepeatBytes

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

RepeatBytes repeat a byte char.

func RepeatChars

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

RepeatChars repeat a byte char.

func RepeatRune

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

RepeatRune repeat a rune char.

func ReplaceAll

go
func ReplaceAll(s string, old string, new string) string

ReplaceAll thay thế tất cả các lần xuất hiện của chuỗi con cũ bằng chuỗi con mới trong chuỗi s cho đến khi chuỗi con cũ không còn tồn tại trong s.

Tham số:

  • s: Chuỗi gốc trong đó sẽ thực hiện thay thế.
  • old: Chuỗi con cần thay thế.
  • new: Chuỗi con thay thế cho chuỗi con cũ.

Trả về:

Chuỗi mới với tất cả các lần xuất hiện của chuỗi con cũ được thay thế bằng chuỗi con mới.

func Replaces

go
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 ReplacesAll

go
func ReplacesAll(s string, new string, olds ...string) string

ReplacesAll thay thế tất cả các chuỗi con trong s bằng chuỗi new. Các chuỗi con cần thay thế được cung cấp trong olds. Lưu ý: Vị trí của new và olds ngược so với ReplaceAll. Thứ tự thay thế sẽ theo thứ tự các chuỗi con trong olds.

Usage:

ReplaceAll(ReplaceAll(ReplaceAll(s, "old3", "new"), "old2", "new"), "old1", "new")
// Or
ReplacesAll(s, "new, "old3", "old2", "old1")

func Resize

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

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

func Rtrim

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

Rtrim alias of TrimRight

func RuneCount

go
func RuneCount(s string) int

RuneCount of the string

func RuneIsLower

go
func RuneIsLower(c rune) bool

RuneIsLower char

func RuneIsUpper

go
func RuneIsUpper(c rune) bool

RuneIsUpper char

func RuneIsWord

go
func RuneIsWord(c rune) bool

RuneIsWord char: a-zA-Z

func RunePos

go
func RunePos(s string, ru rune) int

RunePos alias of the strings.IndexRune

func RuneWidth

go
func RuneWidth(r rune) int

RuneWidth of the rune.

Example:

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

func RunesWidth

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

RunesWidth utf8 runes string width.

Examples:

str := "hi,你好"

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

func SafeBool

go
func SafeBool(s string) bool

SafeBool convert to bool, will ignore error

func SafeByteSize

go
func SafeByteSize(sizeStr string) uint64

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

func SafeFloat32

go
func SafeFloat32(s string) float32

SafeFloat64 convert string to float32, will ignore error

func SafeFloat64

go
func SafeFloat64(s string) float64

SafeFloat64 convert string to float64, will ignore error

func SafeInt

go
func SafeInt(s string) int

SafeInt convert string to int, will ignore error

func SafeInt32

go
func SafeInt32(s string) int32

SafeInt32 convert string to int32, will ignore error

func SafeInt64

go
func SafeInt64(s string) int64

SafeInt64 convert string to int, will ignore error

func SafeString

go
func SafeString(in any) string

SafeString convert value to string, will ignore error

func SafeUint

go
func SafeUint(s string) uint64

SafeUint convert string to uint, will ignore error

func Similarity

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

Similarity calc for two string.

Usage:

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

func SimpleMatch

go
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 Singular

go
func Singular(word string) string

Singular -- Singularize a word.

func SnakeCase

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

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

func Split

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

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

func SplitInlineComment

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

SplitInlineComment for an inline text string.

func SplitKV

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

SplitKV split string to key and value.

func SplitN

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

SplitN string to slice. will filter empty string node.

func SplitNTrimmed

go
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

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

SplitNValid string to slice. will filter empty string node.

func SplitTrimmed

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

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

func SplitValid

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

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

func StandardizedCapitalizeCamel

go
func StandardizedCapitalizeCamel(input string) string

func StandardizedCapitalizeWords

go
func StandardizedCapitalizeWords(input string) string

func StandardizedNumber

go
func StandardizedNumber(number, lenNumber int) string

func StrPos

go
func StrPos(s, sub string) int

StrPos alias of the strings.Index

func String

go
func String(val any) (string, error)

String convert value to string, return error on failed

func StringOr

go
func StringOr(val any, defVal string) string

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

func StringOrDefault

go
func StringOrDefault(val any, defVal string) string

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

func StringOrErr

go
func StringOrErr(val any) (string, error)

StringOrErr convert value to string, return error on failed

func StringOrPanic

go
func StringOrPanic(val any) string

StringOrPanic convert value to string, will panic on error

func Strings

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

Strings alias of the ToSlice()

func StripSlashes

go
func StripSlashes(s string) string

StripSlashes strip slashes for the string.

func Substr

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

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

func SubstrCount

go
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

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

TextSplit alias of the Utf8Split()

func TextTruncate

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

TextTruncate alias of the Utf8Truncate()

func TextWidth

go
func TextWidth(s string) int

TextWidth utf8 string width. alias of RunesWidth()

func TextWrap

go
func TextWrap(s string, w int) string

TextWrap a string by "\n"

func Title

go
func Title(s string) string

Title alias of the strings.ToTitle()

func ToArray

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

ToArray alias of the ToSlice()

func ToBool

go
func ToBool(s string) (bool, error)

ToBool convert string to bool

func ToByteSize

go
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

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

ToBytes converts a string to a byte slice without copy.

func ToDuration

go
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 ToFloat32

go
func ToFloat32(s string) (float32, error)

ToFloat32 convert string to float32, return error on fail

func ToFloat64

go
func ToFloat64(s string) (float64, error)

ToFloat64 convert string to float64, return error on fail

func ToInt

go
func ToInt(s string) (int, error)

ToInt convert string to int, return error on fail

func ToInt32

go
func ToInt32(s string) (int32, error)

ToInt32 convert string to int32, return error on fail

func ToInt64

go
func ToInt64(s string) (int64, error)

ToInt64 convert string to int, return error on fail

func ToIntSlice

go
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

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

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

func ToSlice

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

ToSlice split string to array.

func ToString

go
func ToString(val any) (string, error)

ToString convert value to string, return error on failed

func ToStringWithFunc

go
func ToStringWithFunc(val any, fbFn com_def.ToStringFunc) (str string, err error)

ToStringWithFunc convert value to string, with a func to fallback handle.

On not convert:

  • If fbFn is nil, will return com_def.ErrConvType.
  • If fbFn is not nil, will call it to convert.

func ToStrings

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

ToStrings alias of the ToSlice()

func ToTime

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

ToTime convert date string to time.Time

func ToUint

go
func ToUint(s string) (uint64, error)

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

func Trim

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

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

func TrimCut

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

TrimCut always returns two substring and trim space for items.

func TrimLeft

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

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

func TrimRight

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

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

func Truncate

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

Truncate alias of the Utf8Truncate()

func URLDecode

go
func URLDecode(s string) string

URLDecode decode url string.

func URLEncode

go
func URLEncode(s string) string

URLEncode encode url string.

func Uint

go
func Uint(s string) uint64

Uint convert string to uint, will ignore error

func UintOr

go
func UintOr(s string, defVal uint64) uint64

UintOr convert string to uint, return default value on fail

func UintOrDefault

go
func UintOrDefault(s string, defVal uint64) uint64

UintOrDefault convert string to uint, return default value on fail

func UintOrErr

go
func UintOrErr(s string) (uint64, error)

UintOrErr convert string to uint, return error on fail

func UintOrPanic

go
func UintOrPanic(s string) uint64

UintOrPanic convert value to uint, will panic on error

func Unquote

go
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

go
func Upper(s string) string

Upper alias of the strings.ToUpper()

func UpperFirst

go
func UpperFirst(s string) string

UpperFirst upper first char

func UpperWord

go
func UpperWord(s string) string

UpperWord Change the first character of each word to uppercase

func Uppercase

go
func Uppercase(s string) string

Uppercase alias of the strings.ToUpper()

func Utf8Len

go
func Utf8Len(s string) int

Utf8Len count of the string

func Utf8Split

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

Utf8Split split a string by width.

func Utf8Truncate

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

Utf8Truncate a string with given width.

func Utf8Width

go
func Utf8Width(s string) int

Utf8Width utf8 string width. alias of RunesWidth

func Utf8len

go
func Utf8len(s string) int

Utf8len of the string

func Valid

go
func Valid(ss ...string) string

Valid return first not empty element.

func VersionCompare

go
func VersionCompare(v1, v2, op string) bool

VersionCompare for two version string.

func WidthWrap

go
func WidthWrap(s string, w int) string

WidthWrap a string by "\n"

func WildcardMatch

go
func WildcardMatch(pattern, str string) bool

Match returns true if str matches pattern. This is a very simple wildcard match where '*' matches on any number characters and '?' matches on any one character.

pattern:

{ term }

term:

'*'         matches any sequence of non-Separator characters
'?'         matches any single non-Separator character
c           matches character c (c != '*', '?', '\\')
'\\' c      matches character c

func WildcardMatchLimit

go
func WildcardMatchLimit(pattern, str string, maxcomp int) (matched, stopped bool)

MatchLimit is the same as Match but will limit the complexity of the match operation. This is to avoid long running matches, specifically to avoid ReDos attacks from arbritary inputs.

How it works: The underlying match routine is recursive and may call itself when it encounters a sandwiched wildcard pattern, such as: `user:*:name`. Everytime it calls itself a counter is incremented. The operation is stopped when counter > maxcomp*len(str).

func WordWrap

go
func WordWrap(s string, w int) string

WordWrap text string and limit width.

func WrapTag

go
func WrapTag(s, tag string) string

WrapTag for given string.

func ZeroOr

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

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

type BaseEncoder

BaseEncoder interface

go
type BaseEncoder interface {
    Encode(dst []byte, src []byte)
    EncodeToString(src []byte) string
    Decode(dst []byte, src []byte) (n int, err error)
    DecodeString(s string) ([]byte, error)
}

func Encoding

go
func Encoding(base int, typ BaseType) BaseEncoder

Encoding instance. base: 32 or 64, typ: 0 - 4

Usage:

codec := string_util.Encoding(32, string_util.HexEncoding)
codec := string_util.Encoding(32, string_util.StdEncoding)
codec := string_util.Encoding(64, string_util.URLEncoding)
codec := string_util.Encoding(64, string_util.RawURLEncoding)
codec := string_util.Encoding(64, string_util.RawStdEncoding)
codec := string_util.Encoding(64, string_util.StdEncoding)

type BaseType

BaseType for base encoding

go
type BaseType uint8

types for base encoding

go
const (
    KBaseTypeStd BaseType = iota
    KBaseTypeHex
    KBaseTypeURL
    KBaseTypeRawStd
    KBaseTypeRawURL
)

type Buffer

Buffer wrap and extends the bytes.Buffer

go
type Buffer = byte_util.Buffer

func NewBuffer

go
func NewBuffer() *Buffer

NewBuffer instance

type Builder

Builder struct

go
type Builder struct {
    strings.Builder
}

func (*Builder) ResetGet

go
func (b *Builder) ResetGet() string

ResetGet return current string and reset builder

func (*Builder) Write

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

Write bytes and no error report

func (*Builder) WriteAny

go
func (b *Builder) WriteAny(v any)

WriteAny write any type value.

func (*Builder) WriteAnys

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

WriteAnys write any type values.

func (*Builder) WriteByteNE

go
func (b *Builder) WriteByteNE(c byte)

WriteByteNE write byte and no error report

func (*Builder) WriteMulti

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

WriteMulti write multi byte at once.

func (*Builder) WriteRune

go
func (b *Builder) WriteRune(r rune)

WriteRune and no error report

func (*Builder) WriteString

go
func (b *Builder) WriteString(s string)

WriteString to builder

func (*Builder) WriteStrings

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

WriteStrings write multi string at once.

func (*Builder) Writef

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

Writef write string by fmt.Sprintf formatted

func (*Builder) Writeln

go
func (b *Builder) Writeln(s string)

Writeln write string with newline.

type ByteChanPool

ByteChanPool struct

Usage:

bp := string_util.NewByteChanPool(500, 1024, 1024)
buf:=bp.Get()
defer bp.Put(buf)
// use buf do something ...
go
type ByteChanPool = byte_util.ChanPool

func NewByteChanPool

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

NewByteChanPool instance

type ParseSizeOpt

ParseSizeOpt parse size expression options

go
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)
}

type PosFlag

PosFlag type

go
type PosFlag uint8

Position for padding/resize string

go
const (
    KPosLeft PosFlag = iota
    KPosRight
    KPosMiddle
)

type Rule

Rule -- pluralize rule expression and replacement value.

go
type Rule struct {
    // contains filtered or unexported fields
}

type Runes

Runes data slice

go
type Runes []rune

func (Runes) PadLeft

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

PadLeft a rune to want length

func (Runes) PadRight

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

PadRight a rune to want length

func (Runes) Padding

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

Padding a rune to want length and with position

type SimilarComparator

SimilarComparator definition

links:

https://github.com/mkideal/cli/blob/master/fuzzy.go
go
type SimilarComparator struct {
    // contains filtered or unexported fields
}

func NewComparator

go
func NewComparator(src, dst string) *SimilarComparator

NewComparator create

func (*SimilarComparator) Similar

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

Similar by minDifferRate

Usage:

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

type StrVal

StrVal string. alias of Value

go
type StrVal = Value

type Value

Value string

go
type Value string

func (Value) Bool

go
func (s Value) Bool() bool

Bool convert

func (Value) Bytes

go
func (s Value) Bytes() []byte

Bytes string to bytes

func (Value) HasPrefix

go
func (s Value) HasPrefix(sub string) bool

HasPrefix prefix

func (Value) HasSuffix

go
func (s Value) HasSuffix(sub string) bool

HasSuffix suffix

func (Value) Int

go
func (s Value) Int() int

Int convert

func (Value) Int64

go
func (s Value) Int64() int64

Int64 convert

func (Value) IsBlank

go
func (s Value) IsBlank() bool

IsBlank check

func (Value) IsEmpty

go
func (s Value) IsEmpty() bool

IsEmpty check

func (Value) IsEndWith

go
func (s Value) IsEndWith(sub string) bool

IsEndWith suffix

func (Value) IsStartWith

go
func (s Value) IsStartWith(sub string) bool

IsStartWith prefix

func (Value) OrElse

go
func (s Value) OrElse(or string) string

OrElse string

func (*Value) Set

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

Set value

func (Value) Split

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

Split string

func (Value) SplitN

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

SplitN string

func (Value) String

go
func (s Value) String() string

Value string

func (Value) Val

go
func (s Value) Val() string

Val string

func (Value) WithTrimSpace

go
func (s Value) WithTrimSpace() Value

WithTrimSpace string and return new

Generated by gomarkdoc