stringx

package
v0.2.7 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2022 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	EMAIL          string = "" /* 1208-byte string literal not displayed */
	CreditCard     string = "" /* 151-byte string literal not displayed */
	ISBN10         string = "^(?:[0-9]{9}X|[0-9]{10})$"
	ISBN13         string = "^(?:[0-9]{13})$"
	UUID3          string = "^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$"
	UUID4          string = "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
	UUID5          string = "^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
	UUID           string = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
	Alpha          string = "^[a-zA-Z]+$"
	Alphanumeric   string = "^[a-zA-Z0-9]+$"
	Numeric        string = "^[0-9]+$"
	Int            string = "^(?:[-+]?(?:0|[1-9][0-9]*))$"
	Float          string = "^(?:[-+]?(?:[0-9]+))?(?:\\.[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$"
	Hexadecimal    string = "^[0-9a-fA-F]+$"
	Hexcolor       string = "^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$"
	RGBcolor       string = "" /* 157-byte string literal not displayed */
	ASCII          string = "^[\x00-\x7F]+$"
	Multibyte      string = "[^\x00-\x7F]"
	FullWidth      string = "[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]"
	HalfWidth      string = "[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]"
	Base64         string = "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{4})$"
	PrintableASCII string = "^[\x20-\x7E]+$"
	DataURI        string = "^data:.+\\/(.+);base64$"
	Latitude       string = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$"
	Longitude      string = "^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$"
	DNSName        string = `^([a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62}){1}(\.[a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62})*[\._]?$`
	IP             string = `` /* 659-byte string literal not displayed */
	URLSchema      string = `((ftp|tcp|udp|wss?|https?):\/\/)`
	URLUsername    string = `(\S+(:\S*)?@)`
	URLPath        string = `((\/|\?|#)[^\s]*)`
	URLPort        string = `(:(\d{1,5}))`
	URLIP          string = `([1-9]\d?|1\d\d|2[01]\d|22[0-3])(\.(1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.([0-9]\d?|1\d\d|2[0-4]\d|25[0-4]))`
	URLSubdomain   string = `((www\.)|([a-zA-Z0-9]([-\.][-\._a-zA-Z0-9]+)*))`
	URL            string = `^` + URLSchema + `?` + URLUsername + `?` + `((` + URLIP + `|(\[` + IP + `\])|(([a-zA-Z0-9]([a-zA-Z0-9-_]+)?[a-zA-Z0-9]([-\.][a-zA-Z0-9]+)*)|(` + URLSubdomain + `?))?(([a-zA-Z\x{00a1}-\x{ffff}0-9]+-?-?)*[a-zA-Z\x{00a1}-\x{ffff}0-9]+)(?:\.([a-zA-Z\x{00a1}-\x{ffff}]{1,}))?))\.?` + URLPort + `?` + URLPath + `?$`
	SSN            string = `^\d{3}[- ]?\d{2}[- ]?\d{4}$`
	WinPath        string = `^[a-zA-Z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*$`
	UnixPath       string = `^(/[^/\x00]*)+/?$`
	Semver         string = "" /* 183-byte string literal not displayed */

	Host = `^([\w\d\-_]+\.)+\w+[:\d+]*$`

	PHONE    = "^1[3456789][0-9]{9}$"
	Date     = `^\d{4}-\d{2}-\d{2}$`
	Time     = `^\d{2}:\d{2}:\d{2}$`
	DateTime = `^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$`
	Url      = `(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]`
)

Variables

Escape replace <, >, & and " with HTML entities.

Functions

func BelowLineToCamel added in v0.2.5

func BelowLineToCamel(str string) string

*

  • 下划线连接字符串转大驼峰

func BlackList

func BlackList(str, chars string) string

BlackList remove characters that appear in the blacklist.

func BuildUrl

func BuildUrl(base string, params map[string]string) string

构建请求url

func CamelCaseToUnderscore

func CamelCaseToUnderscore(str string) string

CamelCaseToUnderscore converts from camel case form to underscore separated form. Ex.: MyFunc => my_func

func Center

func Center(str string, length int, pad string) string

Center returns a string with pad string at both side if str's rune length is smaller than length. If str's rune length is larger than length, str itself will be returned.

If pad is an empty string, str will be returned.

Samples:

Center("hello", 4, " ")    => "hello"
Center("hello", 10, " ")   => "  hello   "
Center("hello", 10, "123") => "12hello123"

func Contains

func Contains(str, substring string) bool

Contains check if the string contains the substring.

func Count

func Count(str, pattern string) int

Count how many runes in str match the pattern. Pattern is defined in Translate function.

Samples:

Count("hello", "aeiou") => 3
Count("hello", "a-k")   => 3
Count("hello", "^a-k")  => 2

func Delete

func Delete(str, pattern string) string

Delete runes in str matching the pattern. Pattern is defined in Translate function.

Samples:

Delete("hello", "aeiou") => "hll"
Delete("hello", "a-k")   => "llo"
Delete("hello", "^a-k")  => "he"

func Desensitization added in v0.2.5

func Desensitization(number string, numberType string) string

脱敏号码type:phone手机号,idCard证件号

func ExpandTabs

func ExpandTabs(str string, tabSize int) string

ExpandTabs can expand tabs ('\t') rune in str to one or more spaces dpending on current column and tabSize. The column number is reset to zero after each newline ('\n') occurring in the str.

ExpandTabs uses RuneWidth to decide rune's width. For example, CJK characters will be treated as two characters.

If tabSize <= 0, ExpandTabs panics with error.

Samples:

ExpandTabs("a\tbc\tdef\tghij\tk", 4) => "a   bc  def ghij    k"
ExpandTabs("abcdefg\thij\nk\tl", 4)  => "abcdefg hij\nk   l"
ExpandTabs("z中\t文\tw", 4)           => "z中 文  w"

func Explode

func Explode(src []int, sep string) string

func FirstRuneToLower

func FirstRuneToLower(str string) string

FirstRuneToLower converts first rune to lower case if necessary.

func FirstRuneToUpper

func FirstRuneToUpper(str string) string

FirstRuneToUpper converts first rune to upper case if necessary.

func FormatDateToString added in v0.2.5

func FormatDateToString(datePut string, putTimeTemplate string, outTimeTemplate string) (string, error)

func GetLine

func GetLine(s string, index int) (string, error)

GetLine return specified line of multiline string

func GetLines

func GetLines(s string) []string

GetLines split string by "\n" and return array of lines

func GetUriLocation

func GetUriLocation(str string) string

func GetUrlBase

func GetUrlBase(s string) (string, error)

func GetUrlHost

func GetUrlHost(s string) (string, error)

func GetUrlParam

func GetUrlParam(s string) (url.Values, error)

解析url

func GetUrlRootDomain

func GetUrlRootDomain(s string) (string, error)

func Insert

func Insert(dst, src string, index int) string

Insert src into dst at given rune index. Index is counted by runes instead of bytes.

If index is out of range of dst, panic with out of range.

func IsChinese added in v0.2.5

func IsChinese(str string) bool

判断是否为中文

func IsEmail

func IsEmail(str string) bool

IsEmail check if the string is an email.

func IsFirstUp

func IsFirstUp(str string) bool

func IsFloat

func IsFloat(str string) bool

func IsFloatGreat

func IsFloatGreat(str string, min float64) bool

func IsFloatMin

func IsFloatMin(str string, min float64) bool

func IsHost

func IsHost(str string) bool

func IsNumber

func IsNumber(str string) bool

func IsNumberMin

func IsNumberMin(str string, min int) bool

func IsPhone

func IsPhone(str string) bool

IsEmail check if the string is an email.

func IsUrl

func IsUrl(str string) bool

func LastPartition

func LastPartition(str, sep string) (head, match, tail string)

LastPartition splits a string by last instance of sep into three parts. The return value is a slice of strings with head, match and tail.

If str contains sep, for example "hello" and "l", LastPartition returns

"hel", "l", "o"

If str doesn't contain sep, for example "hello" and "x", LastPartition returns

"", "", "hello"

func LeftJustify

func LeftJustify(str string, length int, pad string) string

LeftJustify returns a string with pad string at right side if str's rune length is smaller than length. If str's rune length is larger than length, str itself will be returned.

If pad is an empty string, str will be returned.

Samples:

LeftJustify("hello", 4, " ")    => "hello"
LeftJustify("hello", 10, " ")   => "hello     "
LeftJustify("hello", 10, "123") => "hello12312"

func LeftTrim

func LeftTrim(str, chars string) string

LeftTrim trim characters from the left-side of the input. If second argument is empty, it's will be remove leading spaces.

func Len

func Len(str string) int

Len returns str's utf8 rune length.

func LowerFirst

func LowerFirst(str string) string

func LowerTitle

func LowerTitle(str string) string

驼峰形式且首字母小写

func Matches

func Matches(str, pattern string) bool

Matches check if string matches the pattern (pattern is regular expression) In case of error return false

func NormalizeEmail

func NormalizeEmail(str string) (string, error)

NormalizeEmail canonicalize an email address. The local part of the email address is lowercased for all domains; the hostname is always lowercased and the local part of the email address is always lowercased for hosts that are known to be case-insensitive (currently only GMail). Normalization follows special rules for known providers: currently, GMail addresses have dots removed in the local part and are stripped of tags (e.g. some.one+tag@gmail.com becomes someone@gmail.com) and all @googlemail.com addresses are normalized to @gmail.com.

func PadBoth

func PadBoth(str string, padStr string, padLen int) string

PadBoth pad sides of string if size of string is less then indicated pad length

func PadLeft

func PadLeft(str string, padStr string, padLen int) string

PadLeft pad left side of string if size of string is less then indicated pad length

func PadRight

func PadRight(str string, padStr string, padLen int) string

PadRight pad right side of string if size of string is less then indicated pad length

func Partition

func Partition(str, sep string) (head, match, tail string)

Partition splits a string by sep into three parts. The return value is a slice of strings with head, match and tail.

If str contains sep, for example "hello" and "l", Partition returns

"he", "l", "lo"

If str doesn't contain sep, for example "hello" and "x", Partition returns

"hello", "", ""

func RandString

func RandString(s int, letters ...string) string

func RandomBase64

func RandomBase64(s int) string

func RandomBytes

func RandomBytes(n int) []byte

func RandomHex

func RandomHex(s int) string

实际就是ASCII码的十六进制 注意长度是s的两倍

func RemoveTags

func RemoveTags(s string) string

RemoveTags remove all tags from HTML string

func ReplacePattern

func ReplacePattern(str, pattern, replace string) string

ReplacePattern replace regular expression pattern in string

func Reverse

func Reverse(s string) string

Reverse return reversed string

func RightJustify

func RightJustify(str string, length int, pad string) string

RightJustify returns a string with pad string at left side if str's rune length is smaller than length. If str's rune length is larger than length, str itself will be returned.

If pad is an empty string, str will be returned.

Samples:

RightJustify("hello", 4, " ")    => "hello"
RightJustify("hello", 10, " ")   => "     hello"
RightJustify("hello", 10, "123") => "12312hello"

func RightTrim

func RightTrim(str, chars string) string

RightTrim trim characters from the right-side of the input. If second argument is empty, it's will be remove spaces.

func RuneSlices

func RuneSlices(r []rune, minLen int) [][]rune

func RuneWidth

func RuneWidth(r rune) int

RuneWidth returns character width in monotype font. Multi-byte characters are usually twice the width of single byte characters.

Algorithm comes from `mb_strwidth` in PHP. http://php.net/manual/en/function.mb-strwidth.php

func SafeFileName

func SafeFileName(str string) string

SafeFileName return safe string that can be used in file names

func Scrub

func Scrub(str, repl string) string

Scrub scrubs invalid utf8 bytes with repl string. Adjacent invalid bytes are replaced only once.

func Shuffle

func Shuffle(str string) string

Shuffle randomizes runes in a string and returns the result. It uses default random source in `math/rand`.

func ShuffleSource

func ShuffleSource(str string, src rand.Source) string

ShuffleSource randomizes runes in a string with given random source.

func Slice

func Slice(str string, start, end int) string

Slice a string by rune.

Start must satisfy 0 <= start <= rune length.

End can be positive, zero or negative. If end >= 0, start and end must satisfy start <= end <= rune length. If end < 0, it means slice to the end of string.

Otherwise, Slice will panic as out of range.

func SortString

func SortString(str string) string

func SpiltColonCommaInt

func SpiltColonCommaInt(str string) (res []map[int]int, err error)

分号数据组即 1:2,3:4

func SpiltCommaInt

func SpiltCommaInt(str string) ([]int, error)

逗号数据组 即 1,2,3

func SpiltCommaMap

func SpiltCommaMap(str string) (res map[string]int, err error)

字符串逗号数组即 a:1,b:2

func Squeeze

func Squeeze(str, pattern string) string

Squeeze deletes adjacent repeated runes in str. If pattern is not empty, only runes matching the pattern will be squeezed.

Samples:

Squeeze("hello", "")             => "helo"
Squeeze("hello", "m-z")          => "hello"
Squeeze("hello   world", " ")    => "hello world"

func StrFirstToUpper added in v0.2.5

func StrFirstToUpper(str string) string

*

  • 首字母转大写

func StringTimeToInt added in v0.2.5

func StringTimeToInt(stringTime string, temp string) (int64, error)

StringTimeToInt 时间日期类型转化为时间戳

func StripLow

func StripLow(str string, keepNewLines bool) string

StripLow remove characters with a numerical value < 32 and 127, mostly control characters. If keep_new_lines is true, newline characters are preserved (\n and \r, hex 0xA and 0xD).

func Substr

func Substr(str string, start int, end int) string

截取字符串 start 起点下标 end 终点下标(不包括)

func Substrs

func Substrs(str string, minLen int) []string

func Successor

func Successor(str string) string

Successor returns the successor to string.

If there is one alphanumeric rune is found in string, increase the rune by 1. If increment generates a "carry", the rune to the left of it is incremented. This process repeats until there is no carry, adding an additional rune if necessary.

If there is no alphanumeric rune, the rightmost rune will be increased by 1 regardless whether the result is a valid rune or not.

Only following characters are alphanumeric.

  • a - z
  • A - Z
  • 0 - 9

Samples (borrowed from ruby's String#succ document):

"abcd"      => "abce"
"THX1138"   => "THX1139"
"<<koala>>" => "<<koalb>>"
"1999zzz"   => "2000aaa"
"ZZZ9999"   => "AAAA0000"
"***"       => "**+"

func SwapCase

func SwapCase(str string) string

SwapCase will swap characters case from upper to lower or lower to upper.

func ToCamelCase

func ToCamelCase(str string) string

ToCamelCase can convert all lower case characters behind underscores to upper case character. Underscore character will be removed in result except following cases.

  • More than 1 underscore. "a__b" => "A_B"
  • At the beginning of string. "_a" => "_A"
  • At the end of string. "ab_" => "Ab_"

func ToSnakeCase

func ToSnakeCase(str string) string

ToSnakeCase can convert all upper case characters in a string to underscore format.

Some samples.

"FirstName"  => "first_name"
"HTTPServer" => "http_server"
"NoHTTPS"    => "no_https"
"GO_PATH"    => "go_path"
"GO PATH"    => "go_path"      // space is converted to underscore.
"GO-PATH"    => "go_path"      // hyphen is converted to underscore.

func Translate

func Translate(str, from, to string) string

Translate str with the characters defined in from replaced by characters defined in to.

From and to are patterns representing a set of characters. Pattern is defined as following.

  • Special characters
  • '-' means a range of runes, e.g.
  • "a-z" means all characters from 'a' to 'z' inclusive;
  • "z-a" means all characters from 'z' to 'a' inclusive.
  • '^' as first character means a set of all runes excepted listed, e.g.
  • "^a-z" means all characters except 'a' to 'z' inclusive.
  • '\' escapes special characters.
  • Normal character represents itself, e.g. "abc" is a set including 'a', 'b' and 'c'.

Translate will try to find a 1:1 mapping from from to to. If to is smaller than from, last rune in to will be used to map "out of range" characters in from.

Note that '^' only works in the from pattern. It will be considered as a normal character in the to pattern.

If the to pattern is an empty string, Translate works exactly the same as Delete.

Samples:

Translate("hello", "aeiou", "12345")    => "h2ll4"
Translate("hello", "a-z", "A-Z")        => "HELLO"
Translate("hello", "z-a", "a-z")        => "svool"
Translate("hello", "aeiou", "*")        => "h*ll*"
Translate("hello", "^l", "*")           => "**ll*"
Translate("hello ^ world", `\^lo`, "*") => "he*** * w*r*d"

func Trim

func Trim(str, chars string) string

Trim trim characters from both sides of the input. If second argument is empty, it's will be remove spaces.

func Truncate

func Truncate(str string, length int, ending string) string

Truncate a string to the closest length without breaking words.

func UUIDString added in v0.2.5

func UUIDString(hasHyphen bool) string

UUIDString 生成uuid hasHyphen 是否需要连字符

func UnderscoreToCamelCase

func UnderscoreToCamelCase(s string) string

UnderscoreToCamelCase converts from underscore separated form to camel case form. Ex.: my_func => MyFunc

func UpcaseFirst

func UpcaseFirst(str string) string

func UrlEncoded

func UrlEncoded(str string) (string, error)

func WhiteList

func WhiteList(str, chars string) string

WhiteList remove characters that do not appear in the whitelist.

func Width

func Width(str string) int

Width returns string width in monotype font. Multi-byte characters are usually twice the width of single byte characters.

Algorithm comes from `mb_strwidth` in PHP. http://php.net/manual/en/function.mb-strwidth.php

func WordCount

func WordCount(str string) int

WordCount returns number of words in a string.

Word is defined as a locale dependent string containing alphabetic characters, which may also contain but not start with `'` and `-` characters.

func WordSplit

func WordSplit(str string) []string

WordSplit splits a string into words. Returns a slice of words. If there is no word in a string, return nil.

Word is defined as a locale dependent string containing alphabetic characters, which may also contain but not start with `'` and `-` characters.

Types

type Translator

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

Translator can translate string with pre-compiled from and to patterns. If a from/to pattern pair needs to be used more than once, it's recommended to create a Translator and reuse it.

func NewTranslator

func NewTranslator(from, to string) *Translator

NewTranslator creates new Translator through a from/to pattern pair.

func (*Translator) HasPattern

func (tr *Translator) HasPattern() bool

HasPattern returns true if Translator has one pattern at least.

func (*Translator) Translate

func (tr *Translator) Translate(str string) string

Translate str with a from/to pattern pair.

See comment in Translate function for usage and samples.

func (*Translator) TranslateRune

func (tr *Translator) TranslateRune(r rune) (result rune, translated bool)

TranslateRune return translated rune and true if r matches the from pattern. If r doesn't match the pattern, original r is returned and translated is false.

Jump to

Keyboard shortcuts

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