pax_global_header00006660000000000000000000000064125422765630014526gustar00rootroot0000000000000052 comment=968bf66e3da857419e4f6e71b2d5c9ae95682dc4 str-1.2.0/000077500000000000000000000000001254227656300123365ustar00rootroot00000000000000str-1.2.0/.gitignore000066400000000000000000000001131254227656300143210ustar00rootroot00000000000000tmp/ *.log _* node_modules example/dist /Gododir/godobin* /Gododir/Gododir str-1.2.0/CREDITS000066400000000000000000000002421254227656300133540ustar00rootroot00000000000000* [string.js](http://stringjs.com) - I contributed several functions to this project. * [bbgen.net](http://bbgen.net/blog/2011/06/string-to-argc-argv/) str-1.2.0/Gododir/000077500000000000000000000000001254227656300137255ustar00rootroot00000000000000str-1.2.0/Gododir/main.go000066400000000000000000000016201254227656300151770ustar00rootroot00000000000000package main import ( "github.com/mgutz/goa" f "github.com/mgutz/goa/filter" "github.com/mgutz/str" do "gopkg.in/godo.v2" "gopkg.in/godo.v2/util" ) // Project is local project. func tasks(p *do.Project) { p.Task("default", do.S{"readme"}, nil) p.Task("install", nil, func(c *do.Context) { c.Run("go get github.com/robertkrimen/godocdown/godocdown") }) p.Task("lint", nil, func(c *do.Context) { c.Run("golint .") c.Run("gofmt -w -s .") c.Run("go vet .") c.Run("go test") }) p.Task("readme", nil, func(c *do.Context) { c.Run("godocdown -output README.md") packageName, _ := util.PackageName("doc.go") // add godoc link goa.Pipe( f.Load("./README.md"), f.Str(str.ReplaceF("--", "\n[godoc](https://godoc.org/"+packageName+")\n", 1)), f.Write(), ) }).Src("**/*.go") p.Task("test", nil, func(c *do.Context) { c.Run("go test") }) } func main() { do.Godo(tasks) } str-1.2.0/LICENSE000066400000000000000000000021241254227656300133420ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2013-2014 Mario L. Gutierrez Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. str-1.2.0/README.md000066400000000000000000000357421254227656300136300ustar00rootroot00000000000000# str import "github.com/mgutz/str" Package str is a comprehensive set of string functions to build more Go awesomeness. Str complements Go's standard packages and does not duplicate functionality found in `strings` or `strconv`. Str is based on plain functions instead of object-based methods, consistent with Go standard string packages. str.Between("foo", "", "") == "foo" Str supports pipelining instead of chaining s := str.Pipe("\nabcdef\n", Clean, BetweenF("a", "f"), ChompLeftF("bc")) User-defined filters can be added to the pipeline by inserting a function or closure that returns a function with this signature func(string) string ### Index * [Variables](#variables) * [func Between](#func [godoc](https://godoc.org/github.com/mgutz/str) between) * [func BetweenF](#func--betweenf) * [func Camelize](#func--camelize) * [func Capitalize](#func--capitalize) * [func CharAt](#func--charat) * [func CharAtF](#func--charatf) * [func ChompLeft](#func--chompleft) * [func ChompLeftF](#func--chompleftf) * [func ChompRight](#func--chompright) * [func ChompRightF](#func--chomprightf) * [func Classify](#func--classify) * [func ClassifyF](#func--classifyf) * [func Clean](#func--clean) * [func Dasherize](#func--dasherize) * [func DecodeHTMLEntities](#func--decodehtmlentities) * [func EnsurePrefix](#func--ensureprefix) * [func EnsurePrefixF](#func--ensureprefixf) * [func EnsureSuffix](#func--ensuresuffix) * [func EnsureSuffixF](#func--ensuresuffixf) * [func EscapeHTML](#func--escapehtml) * [func Humanize](#func--humanize) * [func Iif](#func--iif) * [func IndexOf](#func--indexof) * [func IsAlpha](#func--isalpha) * [func IsAlphaNumeric](#func--isalphanumeric) * [func IsEmpty](#func--isempty) * [func IsLower](#func--islower) * [func IsNumeric](#func--isnumeric) * [func IsUpper](#func--isupper) * [func Left](#func--left) * [func LeftF](#func--leftf) * [func LeftOf](#func--leftof) * [func Letters](#func--letters) * [func Lines](#func--lines) * [func Map](#func--map) * [func Match](#func--match) * [func Pad](#func--pad) * [func PadF](#func--padf) * [func PadLeft](#func--padleft) * [func PadLeftF](#func--padleftf) * [func PadRight](#func--padright) * [func PadRightF](#func--padrightf) * [func Pipe](#func--pipe) * [func QuoteItems](#func--quoteitems) * [func ReplaceF](#func--replacef) * [func ReplacePattern](#func--replacepattern) * [func ReplacePatternF](#func--replacepatternf) * [func Reverse](#func--reverse) * [func Right](#func--right) * [func RightF](#func--rightf) * [func RightOf](#func--rightof) * [func SetTemplateDelimiters](#func--settemplatedelimiters) * [func Slice](#func--slice) * [func SliceContains](#func--slicecontains) * [func SliceF](#func--slicef) * [func SliceIndexOf](#func--sliceindexof) * [func Slugify](#func--slugify) * [func StripPunctuation](#func--strippunctuation) * [func StripTags](#func--striptags) * [func Substr](#func--substr) * [func SubstrF](#func--substrf) * [func Template](#func--template) * [func TemplateDelimiters](#func--templatedelimiters) * [func TemplateWithDelimiters](#func--templatewithdelimiters) * [func ToArgv](#func--toargv) * [func ToBool](#func--tobool) * [func ToBoolOr](#func--toboolor) * [func ToFloat32Or](#func--tofloat32or) * [func ToFloat64Or](#func--tofloat64or) * [func ToIntOr](#func--tointor) * [func Underscore](#func--underscore) * [func UnescapeHTML](#func--unescapehtml) * [func WrapHTML](#func--wraphtml) * [func WrapHTMLF](#func--wraphtmlf) #### Variables ```go var ToFloatOr = ToFloat64Or ``` ToFloatOr parses as a float64 or returns defaultValue. ```go var Verbose = false ``` Verbose flag enables console output for those functions that have counterparts in Go's excellent stadard packages. #### func [Between](#between) ```go func Between(s, left, right string) string ``` Between extracts a string between left and right strings. #### func [BetweenF](#betweenf) ```go func BetweenF(left, right string) func(string) string ``` BetweenF is the filter form for Between. #### func [Camelize](#camelize) ```go func Camelize(s string) string ``` Camelize return new string which removes any underscores or dashes and convert a string into camel casing. #### func [Capitalize](#capitalize) ```go func Capitalize(s string) string ``` Capitalize uppercases the first char of s and lowercases the rest. #### func [CharAt](#charat) ```go func CharAt(s string, index int) string ``` CharAt returns a string from the character at the specified position. #### func [CharAtF](#charatf) ```go func CharAtF(index int) func(string) string ``` CharAtF is the filter form of CharAt. #### func [ChompLeft](#chompleft) ```go func ChompLeft(s, prefix string) string ``` ChompLeft removes prefix at the start of a string. #### func [ChompLeftF](#chompleftf) ```go func ChompLeftF(prefix string) func(string) string ``` ChompLeftF is the filter form of ChompLeft. #### func [ChompRight](#chompright) ```go func ChompRight(s, suffix string) string ``` ChompRight removes suffix from end of s. #### func [ChompRightF](#chomprightf) ```go func ChompRightF(suffix string) func(string) string ``` ChompRightF is the filter form of ChompRight. #### func [Classify](#classify) ```go func Classify(s string) string ``` Classify returns a camelized string with the first letter upper cased. #### func [ClassifyF](#classifyf) ```go func ClassifyF(s string) func(string) string ``` ClassifyF is the filter form of Classify. #### func [Clean](#clean) ```go func Clean(s string) string ``` Clean compresses all adjacent whitespace to a single space and trims s. #### func [Dasherize](#dasherize) ```go func Dasherize(s string) string ``` Dasherize converts a camel cased string into a string delimited by dashes. #### func [DecodeHTMLEntities](#decodehtmlentities) ```go func DecodeHTMLEntities(s string) string ``` DecodeHTMLEntities decodes HTML entities into their proper string representation. DecodeHTMLEntities is an alias for html.UnescapeString #### func [EnsurePrefix](#ensureprefix) ```go func EnsurePrefix(s, prefix string) string ``` EnsurePrefix ensures s starts with prefix. #### func [EnsurePrefixF](#ensureprefixf) ```go func EnsurePrefixF(prefix string) func(string) string ``` EnsurePrefixF is the filter form of EnsurePrefix. #### func [EnsureSuffix](#ensuresuffix) ```go func EnsureSuffix(s, suffix string) string ``` EnsureSuffix ensures s ends with suffix. #### func [EnsureSuffixF](#ensuresuffixf) ```go func EnsureSuffixF(suffix string) func(string) string ``` EnsureSuffixF is the filter form of EnsureSuffix. #### func [EscapeHTML](#escapehtml) ```go func EscapeHTML(s string) string ``` EscapeHTML is alias for html.EscapeString. #### func [Humanize](#humanize) ```go func Humanize(s string) string ``` Humanize transforms s into a human friendly form. #### func [Iif](#iif) ```go func Iif(condition bool, truthy string, falsey string) string ``` Iif is short for immediate if. If condition is true return truthy else falsey. #### func [IndexOf](#indexof) ```go func IndexOf(s string, needle string, start int) int ``` IndexOf finds the index of needle in s starting from start. #### func [IsAlpha](#isalpha) ```go func IsAlpha(s string) bool ``` IsAlpha returns true if a string contains only letters from ASCII (a-z,A-Z). Other letters from other languages are not supported. #### func [IsAlphaNumeric](#isalphanumeric) ```go func IsAlphaNumeric(s string) bool ``` IsAlphaNumeric returns true if a string contains letters and digits. #### func [IsEmpty](#isempty) ```go func IsEmpty(s string) bool ``` IsEmpty returns true if the string is solely composed of whitespace. #### func [IsLower](#islower) ```go func IsLower(s string) bool ``` IsLower returns true if s comprised of all lower case characters. #### func [IsNumeric](#isnumeric) ```go func IsNumeric(s string) bool ``` IsNumeric returns true if a string contains only digits from 0-9. Other digits not in Latin (such as Arabic) are not currently supported. #### func [IsUpper](#isupper) ```go func IsUpper(s string) bool ``` IsUpper returns true if s contains all upper case chracters. #### func [Left](#left) ```go func Left(s string, n int) string ``` Left returns the left substring of length n. #### func [LeftF](#leftf) ```go func LeftF(n int) func(string) string ``` LeftF is the filter form of Left. #### func [LeftOf](#leftof) ```go func LeftOf(s string, needle string) string ``` LeftOf returns the substring left of needle. #### func [Letters](#letters) ```go func Letters(s string) []string ``` Letters returns an array of runes as strings so it can be indexed into. #### func [Lines](#lines) ```go func Lines(s string) []string ``` Lines convert windows newlines to unix newlines then convert to an Array of lines. #### func [Map](#map) ```go func Map(arr []string, iterator func(string) string) []string ``` Map maps an array's iitem through an iterator. #### func [Match](#match) ```go func Match(s, pattern string) bool ``` Match returns true if patterns matches the string #### func [Pad](#pad) ```go func Pad(s, c string, n int) string ``` Pad pads string s on both sides with c until it has length of n. #### func [PadF](#padf) ```go func PadF(c string, n int) func(string) string ``` PadF is the filter form of Pad. #### func [PadLeft](#padleft) ```go func PadLeft(s, c string, n int) string ``` PadLeft pads s on left side with c until it has length of n. #### func [PadLeftF](#padleftf) ```go func PadLeftF(c string, n int) func(string) string ``` PadLeftF is the filter form of PadLeft. #### func [PadRight](#padright) ```go func PadRight(s, c string, n int) string ``` PadRight pads s on right side with c until it has length of n. #### func [PadRightF](#padrightf) ```go func PadRightF(c string, n int) func(string) string ``` PadRightF is the filter form of Padright #### func [Pipe](#pipe) ```go func Pipe(s string, funcs ...func(string) string) string ``` Pipe pipes s through one or more string filters. #### func [QuoteItems](#quoteitems) ```go func QuoteItems(arr []string) []string ``` QuoteItems quotes all items in array, mostly for debugging. #### func [ReplaceF](#replacef) ```go func ReplaceF(old, new string, n int) func(string) string ``` ReplaceF is the filter form of strings.Replace. #### func [ReplacePattern](#replacepattern) ```go func ReplacePattern(s, pattern, repl string) string ``` ReplacePattern replaces string with regexp string. ReplacePattern returns a copy of src, replacing matches of the Regexp with the replacement string repl. Inside repl, $ signs are interpreted as in Expand, so for instance $1 represents the text of the first submatch. #### func [ReplacePatternF](#replacepatternf) ```go func ReplacePatternF(pattern, repl string) func(string) string ``` ReplacePatternF is the filter form of ReplaceRegexp. #### func [Reverse](#reverse) ```go func Reverse(s string) string ``` Reverse a string #### func [Right](#right) ```go func Right(s string, n int) string ``` Right returns the right substring of length n. #### func [RightF](#rightf) ```go func RightF(n int) func(string) string ``` RightF is the Filter version of Right. #### func [RightOf](#rightof) ```go func RightOf(s string, prefix string) string ``` RightOf returns the substring to the right of prefix. #### func [SetTemplateDelimiters](#settemplatedelimiters) ```go func SetTemplateDelimiters(opening, closing string) ``` SetTemplateDelimiters sets the delimiters for Template function. Defaults to "{{" and "}}" #### func [Slice](#slice) ```go func Slice(s string, start, end int) string ``` Slice slices a string. If end is negative then it is the from the end of the string. #### func [SliceContains](#slicecontains) ```go func SliceContains(slice []string, val string) bool ``` SliceContains determines whether val is an element in slice. #### func [SliceF](#slicef) ```go func SliceF(start, end int) func(string) string ``` SliceF is the filter for Slice. #### func [SliceIndexOf](#sliceindexof) ```go func SliceIndexOf(slice []string, val string) int ``` SliceIndexOf gets the indx of val in slice. Returns -1 if not found. #### func [Slugify](#slugify) ```go func Slugify(s string) string ``` Slugify converts s into a dasherized string suitable for URL segment. #### func [StripPunctuation](#strippunctuation) ```go func StripPunctuation(s string) string ``` StripPunctuation strips puncation from string. #### func [StripTags](#striptags) ```go func StripTags(s string, tags ...string) string ``` StripTags strips all of the html tags or tags specified by the parameters #### func [Substr](#substr) ```go func Substr(s string, index int, n int) string ``` Substr returns a substring of s starting at index of length n. #### func [SubstrF](#substrf) ```go func SubstrF(index, n int) func(string) string ``` SubstrF is the filter form of Substr. #### func [Template](#template) ```go func Template(s string, values map[string]interface{}) string ``` Template is a string template which replaces template placeholders delimited by "{{" and "}}" with values from map. The global delimiters may be set with SetTemplateDelimiters. #### func [TemplateDelimiters](#templatedelimiters) ```go func TemplateDelimiters() (opening string, closing string) ``` TemplateDelimiters is the getter for the opening and closing delimiters for Template. #### func [TemplateWithDelimiters](#templatewithdelimiters) ```go func TemplateWithDelimiters(s string, values map[string]interface{}, opening, closing string) string ``` TemplateWithDelimiters is string template with user-defineable opening and closing delimiters. #### func [ToArgv](#toargv) ```go func ToArgv(s string) []string ``` ToArgv converts string s into an argv for exec. #### func [ToBool](#tobool) ```go func ToBool(s string) bool ``` ToBool fuzzily converts truthy values. #### func [ToBoolOr](#toboolor) ```go func ToBoolOr(s string, defaultValue bool) bool ``` ToBoolOr parses s as a bool or returns defaultValue. #### func [ToFloat32Or](#tofloat32or) ```go func ToFloat32Or(s string, defaultValue float32) float32 ``` ToFloat32Or parses as a float32 or returns defaultValue on error. #### func [ToFloat64Or](#tofloat64or) ```go func ToFloat64Or(s string, defaultValue float64) float64 ``` ToFloat64Or parses s as a float64 or returns defaultValue. #### func [ToIntOr](#tointor) ```go func ToIntOr(s string, defaultValue int) int ``` ToIntOr parses s as an int or returns defaultValue. #### func [Underscore](#underscore) ```go func Underscore(s string) string ``` Underscore returns converted camel cased string into a string delimited by underscores. #### func [UnescapeHTML](#unescapehtml) ```go func UnescapeHTML(s string) string ``` UnescapeHTML is an alias for html.UnescapeString. #### func [WrapHTML](#wraphtml) ```go func WrapHTML(s string, tag string, attrs map[string]string) string ``` WrapHTML wraps s within HTML tag having attributes attrs. Note, WrapHTML does not escape s value. #### func [WrapHTMLF](#wraphtmlf) ```go func WrapHTMLF(tag string, attrs map[string]string) func(string) string ``` WrapHTMLF is the filter form of WrapHTML. str-1.2.0/VERSION000066400000000000000000000000061254227656300134020ustar00rootroot000000000000001.1.0 str-1.2.0/doc.go000066400000000000000000000012761254227656300134400ustar00rootroot00000000000000// Package str is a comprehensive set of string functions to build more // Go awesomeness. Str complements Go's standard packages and does not duplicate // functionality found in `strings` or `strconv`. // // Str is based on plain functions instead of object-based methods, // consistent with Go standard string packages. // // str.Between("foo", "", "") == "foo" // // Str supports pipelining instead of chaining // // s := str.Pipe("\nabcdef\n", Clean, BetweenF("a", "f"), ChompLeftF("bc")) // // User-defined filters can be added to the pipeline by inserting a function // or closure that returns a function with this signature // // func(string) string // package str str-1.2.0/funcsAO.go000066400000000000000000000206071254227656300142300ustar00rootroot00000000000000package str import ( "fmt" "html" //"log" "regexp" "strings" ) // Verbose flag enables console output for those functions that have // counterparts in Go's excellent stadard packages. var Verbose = false var templateOpen = "{{" var templateClose = "}}" var beginEndSpacesRe = regexp.MustCompile("^\\s+|\\s+$") var camelizeRe = regexp.MustCompile(`(\-|_|\s)+(.)?`) var camelizeRe2 = regexp.MustCompile(`(\-|_|\s)+`) var capitalsRe = regexp.MustCompile("([A-Z])") var dashSpaceRe = regexp.MustCompile(`[-\s]+`) var dashesRe = regexp.MustCompile("-+") var isAlphaNumericRe = regexp.MustCompile(`[^0-9a-z\xC0-\xFF]`) var isAlphaRe = regexp.MustCompile(`[^a-z\xC0-\xFF]`) var nWhitespaceRe = regexp.MustCompile(`\s+`) var notDigitsRe = regexp.MustCompile(`[^0-9]`) var slugifyRe = regexp.MustCompile(`[^\w\s\-]`) var spaceUnderscoreRe = regexp.MustCompile("[_\\s]+") var spacesRe = regexp.MustCompile("[\\s\\xA0]+") var stripPuncRe = regexp.MustCompile(`[^\w\s]|_`) var templateRe = regexp.MustCompile(`([\-\[\]()*\s])`) var templateRe2 = regexp.MustCompile(`\$`) var underscoreRe = regexp.MustCompile(`([a-z\d])([A-Z]+)`) var whitespaceRe = regexp.MustCompile(`^[\s\xa0]*$`) func min(a, b int) int { if a < b { return a } return b } func max(a, b int) int { if a > b { return a } return b } // Between extracts a string between left and right strings. func Between(s, left, right string) string { l := len(left) startPos := strings.Index(s, left) if startPos < 0 { return "" } endPos := IndexOf(s, right, startPos+l) //log.Printf("%s: left %s right %s start %d end %d", s, left, right, startPos+l, endPos) if endPos < 0 { return "" } else if right == "" { return s[endPos:] } else { return s[startPos+l : endPos] } } // BetweenF is the filter form for Between. func BetweenF(left, right string) func(string) string { return func(s string) string { return Between(s, left, right) } } // Camelize return new string which removes any underscores or dashes and convert a string into camel casing. func Camelize(s string) string { return camelizeRe.ReplaceAllStringFunc(s, func(val string) string { val = strings.ToUpper(val) val = camelizeRe2.ReplaceAllString(val, "") return val }) } // Capitalize uppercases the first char of s and lowercases the rest. func Capitalize(s string) string { return strings.ToUpper(s[0:1]) + strings.ToLower(s[1:]) } // CharAt returns a string from the character at the specified position. func CharAt(s string, index int) string { l := len(s) shortcut := index < 0 || index > l-1 || l == 0 if shortcut { return "" } return s[index : index+1] } // CharAtF is the filter form of CharAt. func CharAtF(index int) func(string) string { return func(s string) string { return CharAt(s, index) } } // ChompLeft removes prefix at the start of a string. func ChompLeft(s, prefix string) string { if strings.HasPrefix(s, prefix) { return s[len(prefix):] } return s } // ChompLeftF is the filter form of ChompLeft. func ChompLeftF(prefix string) func(string) string { return func(s string) string { return ChompLeft(s, prefix) } } // ChompRight removes suffix from end of s. func ChompRight(s, suffix string) string { if strings.HasSuffix(s, suffix) { return s[:len(s)-len(suffix)] } return s } // ChompRightF is the filter form of ChompRight. func ChompRightF(suffix string) func(string) string { return func(s string) string { return ChompRight(s, suffix) } } // Classify returns a camelized string with the first letter upper cased. func Classify(s string) string { return Camelize("-" + s) } // ClassifyF is the filter form of Classify. func ClassifyF(s string) func(string) string { return func(s string) string { return Classify(s) } } // Clean compresses all adjacent whitespace to a single space and trims s. func Clean(s string) string { s = spacesRe.ReplaceAllString(s, " ") s = beginEndSpacesRe.ReplaceAllString(s, "") return s } // Dasherize converts a camel cased string into a string delimited by dashes. func Dasherize(s string) string { s = strings.TrimSpace(s) s = spaceUnderscoreRe.ReplaceAllString(s, "-") s = capitalsRe.ReplaceAllString(s, "-$1") s = dashesRe.ReplaceAllString(s, "-") s = strings.ToLower(s) return s } // EscapeHTML is alias for html.EscapeString. func EscapeHTML(s string) string { if Verbose { fmt.Println("Use html.EscapeString instead of EscapeHTML") } return html.EscapeString(s) } // DecodeHTMLEntities decodes HTML entities into their proper string representation. // DecodeHTMLEntities is an alias for html.UnescapeString func DecodeHTMLEntities(s string) string { if Verbose { fmt.Println("Use html.UnescapeString instead of DecodeHTMLEntities") } return html.UnescapeString(s) } // EnsurePrefix ensures s starts with prefix. func EnsurePrefix(s, prefix string) string { if strings.HasPrefix(s, prefix) { return s } return prefix + s } // EnsurePrefixF is the filter form of EnsurePrefix. func EnsurePrefixF(prefix string) func(string) string { return func(s string) string { return EnsurePrefix(s, prefix) } } // EnsureSuffix ensures s ends with suffix. func EnsureSuffix(s, suffix string) string { if strings.HasSuffix(s, suffix) { return s } return s + suffix } // EnsureSuffixF is the filter form of EnsureSuffix. func EnsureSuffixF(suffix string) func(string) string { return func(s string) string { return EnsureSuffix(s, suffix) } } // Humanize transforms s into a human friendly form. func Humanize(s string) string { if s == "" { return s } s = Underscore(s) var humanizeRe = regexp.MustCompile(`_id$`) s = humanizeRe.ReplaceAllString(s, "") s = strings.Replace(s, "_", " ", -1) s = strings.TrimSpace(s) s = Capitalize(s) return s } // Iif is short for immediate if. If condition is true return truthy else falsey. func Iif(condition bool, truthy string, falsey string) string { if condition { return truthy } return falsey } // IndexOf finds the index of needle in s starting from start. func IndexOf(s string, needle string, start int) int { l := len(s) if needle == "" { if start < 0 { return 0 } else if start < l { return start } else { return l } } if start < 0 || start > l-1 { return -1 } pos := strings.Index(s[start:], needle) if pos == -1 { return -1 } return start + pos } // IsAlpha returns true if a string contains only letters from ASCII (a-z,A-Z). Other letters from other languages are not supported. func IsAlpha(s string) bool { return !isAlphaRe.MatchString(strings.ToLower(s)) } // IsAlphaNumeric returns true if a string contains letters and digits. func IsAlphaNumeric(s string) bool { return !isAlphaNumericRe.MatchString(strings.ToLower(s)) } // IsLower returns true if s comprised of all lower case characters. func IsLower(s string) bool { return IsAlpha(s) && s == strings.ToLower(s) } // IsNumeric returns true if a string contains only digits from 0-9. Other digits not in Latin (such as Arabic) are not currently supported. func IsNumeric(s string) bool { return !notDigitsRe.MatchString(s) } // IsUpper returns true if s contains all upper case chracters. func IsUpper(s string) bool { return IsAlpha(s) && s == strings.ToUpper(s) } // IsEmpty returns true if the string is solely composed of whitespace. func IsEmpty(s string) bool { if s == "" { return true } return whitespaceRe.MatchString(s) } // Left returns the left substring of length n. func Left(s string, n int) string { if n < 0 { return Right(s, -n) } return Substr(s, 0, n) } // LeftF is the filter form of Left. func LeftF(n int) func(string) string { return func(s string) string { return Left(s, n) } } // LeftOf returns the substring left of needle. func LeftOf(s string, needle string) string { return Between(s, "", needle) } // Letters returns an array of runes as strings so it can be indexed into. func Letters(s string) []string { result := []string{} for _, r := range s { result = append(result, string(r)) } return result } // Lines convert windows newlines to unix newlines then convert to an Array of lines. func Lines(s string) []string { s = strings.Replace(s, "\r\n", "\n", -1) return strings.Split(s, "\n") } // Map maps an array's iitem through an iterator. func Map(arr []string, iterator func(string) string) []string { r := []string{} for _, item := range arr { r = append(r, iterator(item)) } return r } // Match returns true if patterns matches the string func Match(s, pattern string) bool { r := regexp.MustCompile(pattern) return r.MatchString(s) } str-1.2.0/funcsPZ.go000066400000000000000000000312371254227656300142630ustar00rootroot00000000000000package str import ( "fmt" "html" //"log" "math" "regexp" "runtime" "strconv" "strings" "unicode/utf8" ) // Pad pads string s on both sides with c until it has length of n. func Pad(s, c string, n int) string { L := len(s) if L >= n { return s } n -= L left := strings.Repeat(c, int(math.Ceil(float64(n)/2))) right := strings.Repeat(c, int(math.Floor(float64(n)/2))) return left + s + right } // PadF is the filter form of Pad. func PadF(c string, n int) func(string) string { return func(s string) string { return Pad(s, c, n) } } // PadLeft pads s on left side with c until it has length of n. func PadLeft(s, c string, n int) string { L := len(s) if L > n { return s } return strings.Repeat(c, (n-L)) + s } // PadLeftF is the filter form of PadLeft. func PadLeftF(c string, n int) func(string) string { return func(s string) string { return PadLeft(s, c, n) } } // PadRight pads s on right side with c until it has length of n. func PadRight(s, c string, n int) string { L := len(s) if L > n { return s } return s + strings.Repeat(c, n-L) } // PadRightF is the filter form of Padright func PadRightF(c string, n int) func(string) string { return func(s string) string { return PadRight(s, c, n) } } // Pipe pipes s through one or more string filters. func Pipe(s string, funcs ...func(string) string) string { for _, fn := range funcs { s = fn(s) } return s } // QuoteItems quotes all items in array, mostly for debugging. func QuoteItems(arr []string) []string { return Map(arr, func(s string) string { return strconv.Quote(s) }) } // ReplaceF is the filter form of strings.Replace. func ReplaceF(old, new string, n int) func(string) string { return func(s string) string { return strings.Replace(s, old, new, n) } } // ReplacePattern replaces string with regexp string. // ReplacePattern returns a copy of src, replacing matches of the Regexp with the replacement string repl. Inside repl, $ signs are interpreted as in Expand, so for instance $1 represents the text of the first submatch. func ReplacePattern(s, pattern, repl string) string { r := regexp.MustCompile(pattern) return r.ReplaceAllString(s, repl) } // ReplacePatternF is the filter form of ReplaceRegexp. func ReplacePatternF(pattern, repl string) func(string) string { return func(s string) string { return ReplacePattern(s, pattern, repl) } } // Reverse a string func Reverse(s string) string { cs := make([]rune, utf8.RuneCountInString(s)) i := len(cs) for _, c := range s { i-- cs[i] = c } return string(cs) } // Right returns the right substring of length n. func Right(s string, n int) string { if n < 0 { return Left(s, -n) } return Substr(s, len(s)-n, n) } // RightF is the Filter version of Right. func RightF(n int) func(string) string { return func(s string) string { return Right(s, n) } } // RightOf returns the substring to the right of prefix. func RightOf(s string, prefix string) string { return Between(s, prefix, "") } // SetTemplateDelimiters sets the delimiters for Template function. Defaults to "{{" and "}}" func SetTemplateDelimiters(opening, closing string) { templateOpen = opening templateClose = closing } // Slice slices a string. If end is negative then it is the from the end // of the string. func Slice(s string, start, end int) string { if end > -1 { return s[start:end] } L := len(s) if L+end > 0 { return s[start : L-end] } return s[start:] } // SliceF is the filter for Slice. func SliceF(start, end int) func(string) string { return func(s string) string { return Slice(s, start, end) } } // SliceContains determines whether val is an element in slice. func SliceContains(slice []string, val string) bool { if slice == nil { return false } for _, it := range slice { if it == val { return true } } return false } // SliceIndexOf gets the indx of val in slice. Returns -1 if not found. func SliceIndexOf(slice []string, val string) int { if slice == nil { return -1 } for i, it := range slice { if it == val { return i } } return -1 } // Slugify converts s into a dasherized string suitable for URL segment. func Slugify(s string) string { sl := slugifyRe.ReplaceAllString(s, "") sl = strings.ToLower(sl) sl = Dasherize(sl) return sl } // StripPunctuation strips puncation from string. func StripPunctuation(s string) string { s = stripPuncRe.ReplaceAllString(s, "") s = nWhitespaceRe.ReplaceAllString(s, " ") return s } // StripTags strips all of the html tags or tags specified by the parameters func StripTags(s string, tags ...string) string { if len(tags) == 0 { tags = append(tags, "") } for _, tag := range tags { stripTagsRe := regexp.MustCompile(`(?i)<\/?` + tag + `[^<>]*>`) s = stripTagsRe.ReplaceAllString(s, "") } return s } // Substr returns a substring of s starting at index of length n. func Substr(s string, index int, n int) string { L := len(s) if index < 0 || index >= L || s == "" { return "" } end := index + n if end >= L { end = L } if end <= index { return "" } return s[index:end] } // SubstrF is the filter form of Substr. func SubstrF(index, n int) func(string) string { return func(s string) string { return Substr(s, index, n) } } // Template is a string template which replaces template placeholders delimited // by "{{" and "}}" with values from map. The global delimiters may be set with // SetTemplateDelimiters. func Template(s string, values map[string]interface{}) string { return TemplateWithDelimiters(s, values, templateOpen, templateClose) } // TemplateDelimiters is the getter for the opening and closing delimiters for Template. func TemplateDelimiters() (opening string, closing string) { return templateOpen, templateClose } // TemplateWithDelimiters is string template with user-defineable opening and closing delimiters. func TemplateWithDelimiters(s string, values map[string]interface{}, opening, closing string) string { escapeDelimiter := func(delim string) string { result := templateRe.ReplaceAllString(delim, "\\$1") return templateRe2.ReplaceAllString(result, "\\$") } openingDelim := escapeDelimiter(opening) closingDelim := escapeDelimiter(closing) r := regexp.MustCompile(openingDelim + `(.+?)` + closingDelim) matches := r.FindAllStringSubmatch(s, -1) for _, submatches := range matches { match := submatches[0] key := submatches[1] //log.Printf("match %s key %s\n", match, key) if values[key] != nil { v := fmt.Sprintf("%v", values[key]) s = strings.Replace(s, match, v, -1) } } return s } // ToArgv converts string s into an argv for exec. func ToArgv(s string) []string { const ( InArg = iota InArgQuote OutOfArg ) currentState := OutOfArg currentQuoteChar := "\x00" // to distinguish between ' and " quotations // this allows to use "foo'bar" currentArg := "" argv := []string{} isQuote := func(c string) bool { return c == `"` || c == `'` } isEscape := func(c string) bool { return c == `\` } isWhitespace := func(c string) bool { return c == " " || c == "\t" } L := len(s) for i := 0; i < L; i++ { c := s[i : i+1] //fmt.Printf("c %s state %v arg %s argv %v i %d\n", c, currentState, currentArg, args, i) if isQuote(c) { switch currentState { case OutOfArg: currentArg = "" fallthrough case InArg: currentState = InArgQuote currentQuoteChar = c case InArgQuote: if c == currentQuoteChar { currentState = InArg } else { currentArg += c } } } else if isWhitespace(c) { switch currentState { case InArg: argv = append(argv, currentArg) currentState = OutOfArg case InArgQuote: currentArg += c case OutOfArg: // nothing } } else if isEscape(c) { switch currentState { case OutOfArg: currentArg = "" currentState = InArg fallthrough case InArg: fallthrough case InArgQuote: if i == L-1 { if runtime.GOOS == "windows" { // just add \ to end for windows currentArg += c } else { panic("Escape character at end string") } } else { if runtime.GOOS == "windows" { peek := s[i+1 : i+2] if peek != `"` { currentArg += c } } else { i++ c = s[i : i+1] currentArg += c } } } } else { switch currentState { case InArg, InArgQuote: currentArg += c case OutOfArg: currentArg = "" currentArg += c currentState = InArg } } } if currentState == InArg { argv = append(argv, currentArg) } else if currentState == InArgQuote { panic("Starting quote has no ending quote.") } return argv } // ToBool fuzzily converts truthy values. func ToBool(s string) bool { s = strings.ToLower(s) return s == "true" || s == "yes" || s == "on" || s == "1" } // ToBoolOr parses s as a bool or returns defaultValue. func ToBoolOr(s string, defaultValue bool) bool { b, err := strconv.ParseBool(s) if err != nil { return defaultValue } return b } // ToIntOr parses s as an int or returns defaultValue. func ToIntOr(s string, defaultValue int) int { n, err := strconv.Atoi(s) if err != nil { return defaultValue } return n } // ToFloat32Or parses as a float32 or returns defaultValue on error. func ToFloat32Or(s string, defaultValue float32) float32 { f, err := strconv.ParseFloat(s, 32) if err != nil { return defaultValue } return float32(f) } // ToFloat64Or parses s as a float64 or returns defaultValue. func ToFloat64Or(s string, defaultValue float64) float64 { f, err := strconv.ParseFloat(s, 64) if err != nil { return defaultValue } return f } // ToFloatOr parses as a float64 or returns defaultValue. var ToFloatOr = ToFloat64Or // TODO This is not working yet. Go's regexp package does not have some // of the niceities in JavaScript // // Truncate truncates the string, accounting for word placement and chars count // adding a morestr (defaults to ellipsis) // func Truncate(s, morestr string, n int) string { // L := len(s) // if L <= n { // return s // } // // if morestr == "" { // morestr = "..." // } // // tmpl := func(c string) string { // if strings.ToUpper(c) != strings.ToLower(c) { // return "A" // } // return " " // } // template := s[0 : n+1] // var truncateRe = regexp.MustCompile(`.(?=\W*\w*$)`) // truncateRe.ReplaceAllStringFunc(template, tmpl) // 'Hello, world' -> 'HellAA AAAAA' // var wwRe = regexp.MustCompile(`\w\w`) // var whitespaceRe2 = regexp.MustCompile(`\s*\S+$`) // if wwRe.MatchString(template[len(template)-2:]) { // template = whitespaceRe2.ReplaceAllString(template, "") // } else { // template = strings.TrimRight(template, " \t\n") // } // // if len(template+morestr) > L { // return s // } // return s[0:len(template)] + morestr // } // // truncate: function(length, pruneStr) { //from underscore.string, author: github.com/rwz // var str = this.s; // // length = ~~length; // pruneStr = pruneStr || '...'; // // if (str.length <= length) return new this.constructor(str); // // var tmpl = function(c){ return c.toUpperCase() !== c.toLowerCase() ? 'A' : ' '; }, // template = str.slice(0, length+1).replace(/.(?=\W*\w*$)/g, tmpl); // 'Hello, world' -> 'HellAA AAAAA' // // if (template.slice(template.length-2).match(/\w\w/)) // template = template.replace(/\s*\S+$/, ''); // else // template = new S(template.slice(0, template.length-1)).trimRight().s; // // return (template+pruneStr).length > str.length ? new S(str) : new S(str.slice(0, template.length)+pruneStr); // }, // Underscore returns converted camel cased string into a string delimited by underscores. func Underscore(s string) string { if s == "" { return "" } u := strings.TrimSpace(s) u = underscoreRe.ReplaceAllString(u, "${1}_$2") u = dashSpaceRe.ReplaceAllString(u, "_") u = strings.ToLower(u) if IsUpper(s[0:1]) { return "_" + u } return u } // UnescapeHTML is an alias for html.UnescapeString. func UnescapeHTML(s string) string { if Verbose { fmt.Println("Use html.UnescapeString instead of UnescapeHTML") } return html.UnescapeString(s) } // WrapHTML wraps s within HTML tag having attributes attrs. Note, // WrapHTML does not escape s value. func WrapHTML(s string, tag string, attrs map[string]string) string { escapeHTMLAttributeQuotes := func(v string) string { v = strings.Replace(v, "<", "<", -1) v = strings.Replace(v, "&", "&", -1) v = strings.Replace(v, "\"", """, -1) return v } if tag == "" { tag = "div" } el := "<" + tag for name, val := range attrs { el += " " + name + "=\"" + escapeHTMLAttributeQuotes(val) + "\"" } el += ">" + s + "" return el } // WrapHTMLF is the filter form of WrapHTML. func WrapHTMLF(tag string, attrs map[string]string) func(string) string { return func(s string) string { return WrapHTML(s, tag, attrs) } } str-1.2.0/str_test.go000066400000000000000000000351161254227656300145420ustar00rootroot00000000000000package str //import "testing" import "fmt" //import "strings" func ExampleBetween() { eg(1, Between("foo", "", "")) eg(2, Between("foo", "", "")) eg(3, Between("foo", "", "")) eg(4, Between("foo", "", "")) eg(5, Between("foo", "", "")) eg(6, Between("Some strings } are very {weird}, dont you think?", "{", "}")) eg(7, Between("This is ateststring", "", "test")) eg(8, Between("This is ateststring", "test", "")) // Output: // 1: foo // 2: foo // 3: foo // 4: foo // 5: // 6: weird // 7: This is a // 8: string } func ExampleBetweenF() { eg(1, Pipe("abc", BetweenF("a", "c"))) // Output: // 1: b } func ExampleCamelize() { eg(1, Camelize("data_rate")) eg(2, Camelize("background-color")) eg(3, Camelize("-moz-something")) eg(4, Camelize("_car_speed_")) eg(5, Camelize("yes_we_can")) // Output: // 1: dataRate // 2: backgroundColor // 3: MozSomething // 4: CarSpeed // 5: yesWeCan } func ExampleCapitalize() { eg(1, Capitalize("abc")) eg(2, Capitalize("ABC")) // Output: // 1: Abc // 2: Abc } func ExampleCharAt() { eg(1, CharAt("abc", 1)) eg(2, CharAt("", -1)) eg(3, CharAt("", 0)) eg(4, CharAt("", 10)) eg(5, CharAt("abc", -1)) eg(6, CharAt("abc", 10)) // Output: // 1: b // 2: // 3: // 4: // 5: // 6: } func ExampleCharAtF() { eg(1, Pipe("abc", CharAtF(1))) // Output: // 1: b } func ExampleChompLeft() { eg(1, ChompLeft("foobar", "foo")) eg(2, ChompLeft("foobar", "bar")) eg(3, ChompLeft("", "foo")) eg(4, ChompLeft("", "")) eg(5, ChompLeft("foo", "")) // Output: // 1: bar // 2: foobar // 3: // 4: // 5: foo } func ExampleChompLeftF() { eg(1, Pipe("abc", ChompLeftF("ab"))) // Output: // 1: c } func ExampleChompRight() { eg(1, ChompRight("foobar", "foo")) eg(2, ChompRight("foobar", "bar")) eg(3, ChompRight("", "foo")) eg(4, ChompRight("", "")) // Output: // 1: foobar // 2: foo // 3: // 4: } func ExampleChompRightF() { eg(1, Pipe("abc", ChompRightF("bc"))) // Output: // 1: a } func ExampleClassify() { eg(1, Classify("data_rate")) eg(2, Classify("background-color")) eg(3, Classify("-moz-something")) eg(4, Classify("_car_speed_")) eg(5, Classify("yes_we_can")) // Output: // 1: DataRate // 2: BackgroundColor // 3: MozSomething // 4: CarSpeed // 5: YesWeCan } func ExampleClean() { eg(1, Clean("clean")) eg(2, Clean("")) eg(3, Clean(" please\t clean \t \n me ")) // Output: // 1: clean // 2: // 3: please clean me } func ExampleDasherize() { eg(1, Dasherize("dataRate")) eg(2, Dasherize("CarSpeed")) eg(3, Dasherize("yesWeCan")) eg(4, Dasherize("")) eg(5, Dasherize("ABC")) // Output: // 1: data-rate // 2: -car-speed // 3: yes-we-can // 4: // 5: -a-b-c } func ExampleDecodeHTMLEntities() { eg(1, DecodeHTMLEntities("Ken Thompson & Dennis Ritchie")) eg(2, DecodeHTMLEntities("3 < 4")) eg(3, DecodeHTMLEntities("http://")) // Output: // 1: Ken Thompson & Dennis Ritchie // 2: 3 < 4 // 3: http:// } func ExampleEnsurePrefix() { eg(1, EnsurePrefix("foobar", "foo")) eg(2, EnsurePrefix("bar", "foo")) eg(3, EnsurePrefix("", "")) eg(4, EnsurePrefix("foo", "")) eg(5, EnsurePrefix("", "foo")) // Output: // 1: foobar // 2: foobar // 3: // 4: foo // 5: foo } func ExampleEnsurePrefixF() { eg(1, Pipe("dir", EnsurePrefixF("./"))) // Output: // 1: ./dir } func ExampleEnsureSuffix() { eg(1, EnsureSuffix("foobar", "bar")) eg(2, EnsureSuffix("foo", "bar")) eg(3, EnsureSuffix("", "")) eg(4, EnsureSuffix("foo", "")) eg(5, EnsureSuffix("", "bar")) // Output: // 1: foobar // 2: foobar // 3: // 4: foo // 5: bar } func ExampleHumanize() { eg(1, Humanize("the_humanize_string_method")) eg(2, Humanize("ThehumanizeStringMethod")) eg(3, Humanize("the humanize string method")) // Output: // 1: The humanize string method // 2: Thehumanize string method // 3: The humanize string method } func ExampleIif() { eg(1, Iif(true, "T", "F")) eg(2, Iif(false, "T", "F")) // Output: // 1: T // 2: F } func ExampleIndexOf() { eg(1, IndexOf("abcdef", "a", 0)) eg(2, IndexOf("abcdef", "a", 3)) eg(3, IndexOf("abcdef", "a", -2)) eg(4, IndexOf("abcdef", "a", 10)) eg(5, IndexOf("", "a", 0)) eg(6, IndexOf("abcdef", "", 2)) eg(7, IndexOf("abcdef", "", 1000)) // Output: // 1: 0 // 2: -1 // 3: -1 // 4: -1 // 5: -1 // 6: 2 // 7: 6 } func ExampleIsAlpha() { eg(1, IsAlpha("afaf")) eg(2, IsAlpha("FJslfjkasfs")) eg(3, IsAlpha("áéúóúÁÉÍÓÚãõÃÕàèìòùÀÈÌÒÙâêîôûÂÊÎÔÛäëïöüÄËÏÖÜçÇ")) eg(4, IsAlpha("adflj43faljsdf")) eg(5, IsAlpha("33")) eg(6, IsAlpha("TT....TTTafafetstYY")) eg(7, IsAlpha("-áéúóúÁÉÍÓÚãõÃÕàèìòùÀÈÌÒÙâêîôûÂÊÎÔÛäëïöüÄËÏÖÜçÇ")) // Output: // 1: true // 2: true // 3: true // 4: false // 5: false // 6: false // 7: false } func eg(index int, example interface{}) { output := fmt.Sprintf("%d: %v", index, example) fmt.Printf("%s\n", Clean(output)) } func ExampleIsAlphaNumeric() { eg(1, IsAlphaNumeric("afaf35353afaf")) eg(2, IsAlphaNumeric("FFFF99fff")) eg(3, IsAlphaNumeric("99")) eg(4, IsAlphaNumeric("afff")) eg(5, IsAlphaNumeric("Infinity")) eg(6, IsAlphaNumeric("áéúóúÁÉÍÓÚãõÃÕàèìòùÀÈÌÒÙâêîôûÂÊÎÔÛäëïöüÄËÏÖÜçÇ1234567890")) eg(7, IsAlphaNumeric("-Infinity")) eg(8, IsAlphaNumeric("-33")) eg(9, IsAlphaNumeric("aaff..")) eg(10, IsAlphaNumeric(".áéúóúÁÉÍÓÚãõÃÕàèìòùÀÈÌÒÙâêîôûÂÊÎÔÛäëïöüÄËÏÖÜçÇ1234567890")) // Output: // 1: true // 2: true // 3: true // 4: true // 5: true // 6: true // 7: false // 8: false // 9: false // 10: false } func ExampleIsEmpty() { eg(1, IsEmpty(" ")) eg(2, IsEmpty("\t\t\t ")) eg(3, IsEmpty("\t\n ")) eg(4, IsEmpty("hi")) // Output: // 1: true // 2: true // 3: true // 4: false } func ExampleIsLower() { eg(1, IsLower("a")) eg(2, IsLower("A")) eg(3, IsLower("abc")) eg(4, IsLower("aBc")) eg(5, IsLower("áéúóúãõàèìòùâêîôûäëïöüç")) eg(6, IsLower("hi jp")) eg(7, IsLower("ÁÉÍÓÚÃÕÀÈÌÒÙÂÊÎÔÛÄËÏÖÜÇ")) eg(8, IsLower("áéúóúãõàèìòùâêîôûäëïöüçÁ")) eg(9, IsLower("áéúóúãõàèìòùâêîôû äëïöüç")) // Output: // 1: true // 2: false // 3: true // 4: false // 5: true // 6: false // 7: false // 8: false // 9: false } func ExampleIsNumeric() { eg(1, IsNumeric("3")) eg(2, IsNumeric("34.22")) eg(3, IsNumeric("-22.33")) eg(4, IsNumeric("NaN")) eg(5, IsNumeric("Infinity")) eg(6, IsNumeric("-Infinity")) eg(7, IsNumeric("JP")) eg(8, IsNumeric("-5")) eg(9, IsNumeric("00099242424")) // Output: // 1: true // 2: false // 3: false // 4: false // 5: false // 6: false // 7: false // 8: false // 9: true } func ExampleIsUpper() { eg(1, IsUpper("a")) eg(2, IsUpper("A")) eg(3, IsUpper("ABC")) eg(4, IsUpper("aBc")) eg(5, IsUpper("áéúóúãõàèìòùâêîôûäëïöüç")) eg(6, IsUpper("HI JP")) eg(7, IsUpper("ÁÉÍÓÚÃÕÀÈÌÒÙÂÊÎÔÛÄËÏÖÜÇ")) eg(8, IsUpper("áéúóúãõàèìòùâêîôûäëïöüçÁ")) eg(9, IsUpper("ÁÉÍÓÚÃÕÀÈÌÒÙÂÊÎ ÔÛÄËÏÖÜÇ")) // Output: // 1: false // 2: true // 3: true // 4: false // 5: false // 6: false // 7: true // 8: false // 9: false } func ExampleLeft() { eg(1, Left("abcdef", 0)) eg(2, Left("abcdef", 1)) eg(3, Left("abcdef", 4)) eg(4, Left("abcdef", -2)) // Output: // 1: // 2: a // 3: abcd // 4: ef } func ExampleLeftOf() { eg(1, LeftOf("abcdef", "def")) eg(2, LeftOf("abcdef", "abc")) eg(3, LeftOf("abcdef", "")) eg(4, LeftOf("", "abc")) eg(5, LeftOf("abcdef", "xyz")) // Output: // 1: abc // 2: // 3: abcdef // 4: // 5: } func ExampleLines() { eg(1, Lines("a\r\nb\nc\r\n")) eg(2, Lines("a\r\nb\nc\r\nd")) // Output: // 1: [a b c ] // 2: [a b c d] } func ExampleMatch() { eg(1, Match("foobar", `^fo.*r$`)) eg(2, Match("foobar", `^fo.*x$`)) eg(3, Match("", `^fo.*x$`)) // Output: // 1: true // 2: false // 3: false } func ExamplePad() { eg(1, Pad("hello", "x", 5)) eg(2, Pad("hello", "x", 10)) eg(3, Pad("hello", "x", 11)) eg(4, Pad("hello", "x", 6)) eg(5, Pad("hello", "x", 1)) // Output: // 1: hello // 2: xxxhelloxx // 3: xxxhelloxxx // 4: xhello // 5: hello } func ExamplePadLeft() { eg(1, PadLeft("hello", "x", 5)) eg(2, PadLeft("hello", "x", 10)) eg(3, PadLeft("hello", "x", 11)) eg(4, PadLeft("hello", "x", 6)) eg(5, PadLeft("hello", "x", 1)) // Output: // 1: hello // 2: xxxxxhello // 3: xxxxxxhello // 4: xhello // 5: hello } func ExamplePadRight() { eg(1, PadRight("hello", "x", 5)) eg(2, PadRight("hello", "x", 10)) eg(3, PadRight("hello", "x", 11)) eg(4, PadRight("hello", "x", 6)) eg(5, PadRight("hello", "x", 1)) // Output: // 1: hello // 2: helloxxxxx // 3: helloxxxxxx // 4: hellox // 5: hello } func ExamplePipe() { eg(1, Pipe("\nabcdef \n", Clean, BetweenF("a", "f"), ChompLeftF("bc"))) // Output: // 1: de } func ExampleReplaceF() { eg(1, Pipe("abcdefab", ReplaceF("ab", "x", -1))) eg(2, Pipe("abcdefab", ReplaceF("ab", "x", 1))) eg(3, Pipe("abcdefab", ReplaceF("ab", "x", 0))) // Output: // 1: xcdefx // 2: xcdefab // 3: abcdefab } func ExampleReplacePattern() { eg(1, ReplacePattern("aabbcc", `a`, "x")) // Output: // 1: xxbbcc } func ExampleReplacePatternF() { eg(1, Pipe("aabbcc", ReplacePatternF(`a`, "x"))) // Output: // 1: xxbbcc } func ExampleReverse() { eg(1, Reverse("abc")) eg(2, Reverse("中文")) // Output: // 1: cba // 2: 文中 } func ExampleRight() { eg(1, Right("abcdef", 0)) eg(2, Right("abcdef", 1)) eg(3, Right("abcdef", 4)) eg(4, Right("abcdef", -2)) // Output: // 1: // 2: f // 3: cdef // 4: ab } func ExampleRightOf() { eg(1, RightOf("abcdef", "abc")) eg(2, RightOf("abcdef", "def")) eg(3, RightOf("abcdef", "")) eg(4, RightOf("", "abc")) eg(5, RightOf("abcdef", "xyz")) // Output: // 1: def // 2: // 3: abcdef // 4: // 5: } func ExampleRightF() { eg(1, Pipe("abcdef", RightF(3))) // Output: // 1: def } func ExampleSliceContains() { eg(1, SliceContains([]string{"foo", "bar"}, "foo")) eg(2, SliceContains(nil, "foo")) eg(3, SliceContains([]string{"foo", "bar"}, "bah")) eg(4, SliceContains([]string{"foo", "bar"}, "")) // Output: // 1: true // 2: false // 3: false // 4: false } func ExampleSliceIndexOf() { eg(1, SliceIndexOf([]string{"foo", "bar"}, "foo")) eg(2, SliceIndexOf(nil, "foo")) eg(3, SliceIndexOf([]string{"foo", "bar"}, "bah")) eg(4, SliceIndexOf([]string{"foo", "bar"}, "")) eg(5, SliceIndexOf([]string{"foo", "bar"}, "bar")) // Output: // 1: 0 // 2: -1 // 3: -1 // 4: -1 // 5: 1 } func ExampleSlugify() { eg(1, Slugify("foo bar")) eg(2, Slugify("foo/bar bah")) eg(3, Slugify("foo-bar--bah")) // Output: // 1: foo-bar // 2: foobar-bah // 3: foo-bar-bah } func ExampleStripPunctuation() { eg(1, StripPunctuation("My, st[ring] *full* of %punct)")) // Output: // 1: My string full of punct } func ExampleStripTags() { eg(1, StripTags("

just some text

")) eg(2, StripTags("

just some text

", "p")) eg(3, StripTags("

just some text

", "a", "p")) eg(4, StripTags("

just some text

", "b")) // Output: // 1: just some text // 2: just some text // 3: just some text // 4:

just some text

} func ExampleSubstr() { eg(1, Substr("abcdef", 2, -1)) eg(2, Substr("abcdef", 2, 0)) eg(3, Substr("abcdef", 2, 1)) eg(4, Substr("abcdef", 2, 3)) eg(5, Substr("abcdef", 2, 4)) eg(6, Substr("abcdef", 2, 100)) eg(7, Substr("abcdef", 0, 1)) // Output: // 1: // 2: // 3: c // 4: cde // 5: cdef // 6: cdef // 7: a } func ExampleTemplateWithDelimiters() { eg(1, TemplateWithDelimiters("Hello {{name}} at {{date-year}}", map[string]interface{}{"name": "foo", "date-year": 2014}, "{{", "}}")) eg(2, TemplateWithDelimiters("Hello #{name} at #{date-year}", map[string]interface{}{"name": "foo", "date-year": 2014}, "#{", "}")) eg(3, TemplateWithDelimiters("Hello (name) at (date-year)", map[string]interface{}{"name": "foo", "date-year": 2014}, "(", ")")) eg(4, TemplateWithDelimiters("Hello [name] at [date-year]", map[string]interface{}{"name": "foo", "date-year": 2014}, "[", "]")) eg(5, TemplateWithDelimiters("Hello *name* at *date-year*", map[string]interface{}{"name": "foo", "date-year": 2014}, "*", "*")) eg(6, TemplateWithDelimiters("Hello $name$ at $date-year$", map[string]interface{}{"name": "foo", "date-year": 2014}, "$", "$")) // Output: // 1: Hello foo at 2014 // 2: Hello foo at 2014 // 3: Hello foo at 2014 // 4: Hello foo at 2014 // 5: Hello foo at 2014 // 6: Hello foo at 2014 } func ExampleTemplate() { eg(1, Template("Hello {{name}} at {{date-year}}", map[string]interface{}{"name": "foo", "date-year": 2014})) eg(2, Template("Hello {{name}}", map[string]interface{}{"name": ""})) SetTemplateDelimiters("{", "}") eg(3, Template("Hello {name} at {date-year}", map[string]interface{}{"name": "foo", "date-year": 2014})) // Output: // 1: Hello foo at 2014 // 2: Hello // 3: Hello foo at 2014 } func ExampleToArgv() { eg(1, QuoteItems(ToArgv(`GO_ENV=test gosu --watch foo@release "some quoted string 'inside'"`))) eg(2, QuoteItems(ToArgv(`gosu foo\ bar`))) eg(3, QuoteItems(ToArgv(`gosu --test="some arg" -w -s a=123`))) // Output: // 1: ["GO_ENV=test" "gosu" "--watch" "foo@release" "some quoted string 'inside'"] // 2: ["gosu" "foo bar"] // 3: ["gosu" "--test=some arg" "-w" "-s" "a=123"] } func ExampleToBool() { eg(1, ToBool("true")) eg(2, ToBool("yes")) eg(3, ToBool("1")) eg(4, ToBool("on")) eg(5, ToBool("false")) eg(6, ToBool("no")) eg(7, ToBool("0")) eg(8, ToBool("off")) eg(9, ToBool("")) eg(10, ToBool("?")) // Output: // 1: true // 2: true // 3: true // 4: true // 5: false // 6: false // 7: false // 8: false // 9: false // 10: false } func ExampleToBoolOr() { eg(1, ToBoolOr("foo", true)) eg(2, ToBoolOr("foo", false)) eg(3, ToBoolOr("true", false)) eg(4, ToBoolOr("", true)) // Output: // 1: true // 2: false // 3: true // 4: true } func ExampleToIntOr() { eg(1, ToIntOr("foo", 0)) eg(2, ToIntOr("", 1)) eg(3, ToIntOr("100", 0)) eg(4, ToIntOr("-1", 1)) // Output: // 1: 0 // 2: 1 // 3: 100 // 4: -1 } func ExampleUnderscore() { eg(1, Underscore("fooBar")) eg(2, Underscore("FooBar")) eg(3, Underscore("")) eg(4, Underscore("x")) // Output: // 1: foo_bar // 2: _foo_bar // 3: // 4: x } func ExampleWrapHTML() { eg(1, WrapHTML("foo", "span", nil)) eg(2, WrapHTML("foo", "", nil)) eg(3, WrapHTML("foo", "", map[string]string{"class": "bar"})) // Output: // 1: foo // 2:
foo
// 3:
foo
} func ExampleWrapHTMLF() { eg(1, Pipe("foo", WrapHTMLF("div", nil))) // Output: // 1:
foo
}