Documentation ¶
Index ¶
- Constants
- Variables
- func BelowLineToCamel(str string) string
- func BlackList(str, chars string) string
- func BuildUrl(base string, params map[string]string) string
- func CamelCaseToUnderscore(str string) string
- func Center(str string, length int, pad string) string
- func Contains(str, substring string) bool
- func Count(str, pattern string) int
- func Delete(str, pattern string) string
- func Desensitization(number string, numberType string) string
- func ExpandTabs(str string, tabSize int) string
- func Explode(src []int, sep string) string
- func FirstRuneToLower(str string) string
- func FirstRuneToUpper(str string) string
- func FormatDateToString(datePut string, putTimeTemplate string, outTimeTemplate string) (string, error)
- func GetLine(s string, index int) (string, error)
- func GetLines(s string) []string
- func GetUriLocation(str string) string
- func GetUrlBase(s string) (string, error)
- func GetUrlHost(s string) (string, error)
- func GetUrlParam(s string) (url.Values, error)
- func GetUrlRootDomain(s string) (string, error)
- func Insert(dst, src string, index int) string
- func IsChinese(str string) bool
- func IsEmail(str string) bool
- func IsFirstUp(str string) bool
- func IsFloat(str string) bool
- func IsFloatGreat(str string, min float64) bool
- func IsFloatMin(str string, min float64) bool
- func IsHost(str string) bool
- func IsNumber(str string) bool
- func IsNumberMin(str string, min int) bool
- func IsPhone(str string) bool
- func IsUrl(str string) bool
- func LastPartition(str, sep string) (head, match, tail string)
- func LeftJustify(str string, length int, pad string) string
- func LeftTrim(str, chars string) string
- func Len(str string) int
- func LowerFirst(str string) string
- func LowerTitle(str string) string
- func Matches(str, pattern string) bool
- func NormalizeEmail(str string) (string, error)
- func PadBoth(str string, padStr string, padLen int) string
- func PadLeft(str string, padStr string, padLen int) string
- func PadRight(str string, padStr string, padLen int) string
- func Partition(str, sep string) (head, match, tail string)
- func RandString(s int, letters ...string) string
- func RandomBase64(s int) string
- func RandomBytes(n int) []byte
- func RandomHex(s int) string
- func RemoveTags(s string) string
- func ReplacePattern(str, pattern, replace string) string
- func Reverse(s string) string
- func RightJustify(str string, length int, pad string) string
- func RightTrim(str, chars string) string
- func RuneSlices(r []rune, minLen int) [][]rune
- func RuneWidth(r rune) int
- func SafeFileName(str string) string
- func Scrub(str, repl string) string
- func Shuffle(str string) string
- func ShuffleSource(str string, src rand.Source) string
- func Slice(str string, start, end int) string
- func SortString(str string) string
- func SpiltColonCommaInt(str string) (res []map[int]int, err error)
- func SpiltCommaInt(str string) ([]int, error)
- func SpiltCommaMap(str string) (res map[string]int, err error)
- func Squeeze(str, pattern string) string
- func StrFirstToUpper(str string) string
- func StringTimeToInt(stringTime string, temp string) (int64, error)
- func StripLow(str string, keepNewLines bool) string
- func Substr(str string, start int, end int) string
- func Substrs(str string, minLen int) []string
- func Successor(str string) string
- func SwapCase(str string) string
- func ToCamelCase(str string) string
- func ToSnakeCase(str string) string
- func Translate(str, from, to string) string
- func Trim(str, chars string) string
- func Truncate(str string, length int, ending string) string
- func UUIDString(hasHyphen bool) string
- func UnderscoreToCamelCase(s string) string
- func UpcaseFirst(str string) string
- func UrlEncoded(str string) (string, error)
- func WhiteList(str, chars string) string
- func Width(str string) int
- func WordCount(str string) int
- func WordSplit(str string) []string
- type Translator
Constants ¶
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 ¶
var Escape = html.EscapeString
Escape replace <, >, & and " with HTML entities.
Functions ¶
func CamelCaseToUnderscore ¶
CamelCaseToUnderscore converts from camel case form to underscore separated form. Ex.: MyFunc => my_func
func Center ¶
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 Count ¶
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 ¶
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
脱敏号码type:phone手机号,idCard证件号
func ExpandTabs ¶
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 FirstRuneToLower ¶
FirstRuneToLower converts first rune to lower case if necessary.
func FirstRuneToUpper ¶
FirstRuneToUpper converts first rune to upper case if necessary.
func FormatDateToString ¶ added in v0.2.5
func GetUriLocation ¶
func GetUrlBase ¶
func GetUrlHost ¶
func GetUrlRootDomain ¶
func Insert ¶
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 IsFloatGreat ¶
func IsFloatMin ¶
func IsNumberMin ¶
func LastPartition ¶
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 ¶
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 ¶
LeftTrim trim characters from the left-side of the input. If second argument is empty, it's will be remove leading spaces.
func LowerFirst ¶
func Matches ¶
Matches check if string matches the pattern (pattern is regular expression) In case of error return false
func NormalizeEmail ¶
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 PadRight ¶
PadRight pad right side of string if size of string is less then indicated pad length
func Partition ¶
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 RandomBase64 ¶
func RandomBytes ¶
func ReplacePattern ¶
ReplacePattern replace regular expression pattern in string
func RightJustify ¶
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 ¶
RightTrim trim characters from the right-side of the input. If second argument is empty, it's will be remove spaces.
func RuneSlices ¶
func RuneWidth ¶
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 ¶
SafeFileName return safe string that can be used in file names
func Scrub ¶
Scrub scrubs invalid utf8 bytes with repl string. Adjacent invalid bytes are replaced only once.
func Shuffle ¶
Shuffle randomizes runes in a string and returns the result. It uses default random source in `math/rand`.
func ShuffleSource ¶
ShuffleSource randomizes runes in a string with given random source.
func Slice ¶
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 SpiltColonCommaInt ¶
分号数据组即 1:2,3:4
func SpiltCommaMap ¶
字符串逗号数组即 a:1,b:2
func Squeeze ¶
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 StringTimeToInt ¶ added in v0.2.5
StringTimeToInt 时间日期类型转化为时间戳
func StripLow ¶
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 Successor ¶
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 ToCamelCase ¶
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 ¶
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 ¶
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 ¶
Trim trim characters from both sides of the input. If second argument is empty, it's will be remove spaces.
func UUIDString ¶ added in v0.2.5
UUIDString 生成uuid hasHyphen 是否需要连字符
func UnderscoreToCamelCase ¶
UnderscoreToCamelCase converts from underscore separated form to camel case form. Ex.: my_func => MyFunc
func UpcaseFirst ¶
func UrlEncoded ¶
func Width ¶
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 ¶
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.
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.