当前位置: 首页>>代码示例>>Golang>>正文


Golang strings.FieldsFunc函数代码示例

本文整理汇总了Golang中strings.FieldsFunc函数的典型用法代码示例。如果您正苦于以下问题:Golang FieldsFunc函数的具体用法?Golang FieldsFunc怎么用?Golang FieldsFunc使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了FieldsFunc函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: receive

//receive from client
func receive(in string) (ret []string) {
	fmt.Printf("Received: %s\n", in)
	var response string
	var answer = make(chan string, 3)
	sf := func(c rune) bool {
		return c == ',' || c == ',' || c == ';' || c == '。' || c == '.' || c == '?' || c == '?'
	}
	if chinese(in) {
		go func() {
			if ret := iceAI(in); ret != "" {
				answer <- ret
			}
		}()
		go func() {
			if ret := tlAI(in); ret != "" {
				answer <- ret
			}
		}()
		go func() {
			if ret := qinAI(in); ret != "" {
				answer <- strings.Replace(ret, "Jarvis", "samaritan", -1)
			}
		}()
		response = <-answer // accept the first reply
		// Separate into fields with func.
		ret = strings.FieldsFunc(response, sf)

	} else {
		response = mitAI(in)
		ret = strings.FieldsFunc(response, sf)
	}
	return
}
开发者ID:evolsnow,项目名称:robot,代码行数:34,代码来源:main.go

示例2: isSameOrNewer

// isSameOrNewer go version (goA.B)
// go1.6 >= go1.6 == true
// go1.5 >= go1.6 == false
func isSameOrNewer(base, check string) bool {
	if base == check {
		return true
	}
	if strings.HasPrefix(check, "devel-") {
		return true
	}
	bp := strings.FieldsFunc(base, GoVersionFields)
	cp := strings.FieldsFunc(check, GoVersionFields)
	if len(bp) < 2 || len(cp) < 2 {
		log.Fatalf("Error comparing %s to %s\n", base, check)
	}
	if bp[0] == cp[0] { // We only have go version 1 right now
		bm, err := strconv.Atoi(bp[1])
		// These errors are unlikely and there is nothing nice to do here anyway
		if err != nil {
			panic(err)
		}
		cm, err := strconv.Atoi(cp[1])
		if err != nil {
			panic(err)
		}
		return cm >= bm
	}
	return false
}
开发者ID:li-ang,项目名称:godep,代码行数:29,代码来源:version.go

示例3: ApplyBuildConstraints

// parse and filter list of platforms
func ApplyBuildConstraints(buildConstraints string, unfilteredPlatforms []Platform) []Platform {
	ret := []Platform{}
	items := strings.FieldsFunc(buildConstraints, func(r rune) bool { return r == ' ' })
	if len(items) == 0 {
		return unfilteredPlatforms
	}
	for _, item := range items {
		parts := strings.FieldsFunc(item, func(r rune) bool { return r == ',' })
		itemOs := []string{}
		itemNegOs := []string{}
		itemArch := []string{}
		itemNegArch := []string{}
		for _, part := range parts {
			isNeg, modulus := isNegative(part)
			if IsOs(modulus) {
				if isNeg {
					itemNegOs = append(itemNegOs, modulus)
				} else {
					itemOs = append(itemOs, modulus)
				}
			} else if IsArch(modulus) {
				if isNeg {
					itemNegArch = append(itemNegArch, modulus)
				} else {
					itemArch = append(itemArch, modulus)
				}

			} else {
				log.Printf("Unrecognised build constraint! Ignoring '%s'", part)
			}
		}
		ret = append(ret, resolveItem(itemOs, itemNegOs, itemArch, itemNegArch, unfilteredPlatforms)...)
	}
	return ret
}
开发者ID:kc87654321,项目名称:goxc,代码行数:36,代码来源:buildconstraints.go

示例4: parseRules

func (r *Rules) parseRules(expression string, onRule func(functionName string, function interface{}, arguments []string) error) error {
	functions := map[string]interface{}{
		"Host":            r.host,
		"HostRegexp":      r.hostRegexp,
		"Path":            r.path,
		"PathStrip":       r.pathStrip,
		"PathPrefix":      r.pathPrefix,
		"PathPrefixStrip": r.pathPrefixStrip,
		"Method":          r.methods,
		"Headers":         r.headers,
		"HeadersRegexp":   r.headersRegexp,
	}

	if len(expression) == 0 {
		return errors.New("Empty rule")
	}

	f := func(c rune) bool {
		return c == ':'
	}

	// Allow multiple rules separated by ;
	splitRule := func(c rune) bool {
		return c == ';'
	}

	parsedRules := strings.FieldsFunc(expression, splitRule)

	for _, rule := range parsedRules {
		// get function
		parsedFunctions := strings.FieldsFunc(rule, f)
		if len(parsedFunctions) == 0 {
			return errors.New("Error parsing rule: '" + rule + "'")
		}
		functionName := strings.TrimSpace(parsedFunctions[0])
		parsedFunction, ok := functions[functionName]
		if !ok {
			return errors.New("Error parsing rule: '" + rule + "'. Unknown function: '" + parsedFunctions[0] + "'")
		}
		parsedFunctions = append(parsedFunctions[:0], parsedFunctions[1:]...)
		fargs := func(c rune) bool {
			return c == ','
		}
		// get function
		parsedArgs := strings.FieldsFunc(strings.Join(parsedFunctions, ":"), fargs)
		if len(parsedArgs) == 0 {
			return errors.New("Error parsing args from rule: '" + rule + "'")
		}

		for i := range parsedArgs {
			parsedArgs[i] = strings.TrimSpace(parsedArgs[i])
		}

		err := onRule(functionName, parsedFunction, parsedArgs)
		if err != nil {
			return fmt.Errorf("Parsing error on rule: %v", err)
		}
	}
	return nil
}
开发者ID:vdemeester,项目名称:traefik,代码行数:60,代码来源:rules.go

示例5: openID

func openID(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	url := *r.URL
	url.Scheme = "http"
	url.Host = "localhost:8080"
	if r.Form.Get("openid.ns") == "" {
		req := openid.Request{
			ReturnTo:     url.String(),
			Teams:        strings.FieldsFunc(*teams, isComma),
			SRegRequired: strings.FieldsFunc(*required, isComma),
			SRegOptional: strings.FieldsFunc(*optional, isComma),
		}
		url := client.RedirectURL(&req)
		http.Redirect(w, r, url, http.StatusFound)
		return
	}
	resp, err := client.Verify(url.String())
	w.Header().Set("ContentType", "text/html")
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		errorTemplate.Execute(w, err)
		return
	}
	loginTemplate.Execute(w, resp)
}
开发者ID:juju,项目名称:usso,代码行数:25,代码来源:main.go

示例6: parseParameters

func parseParameters(params string) Params {
	pairs := strings.FieldsFunc(params, splitQuotedOn(';'))
	r := make(map[string][]string, len(pairs))
	for _, pair := range pairs {
		values := strings.FieldsFunc(pair, splitQuotedOn('=', ','))
		key := values[0]
		if len(pair) == 1 {
			r[key] = append(r[key], "")
			continue
		}
		for i := 1; i < len(values); i++ {
			val := values[i]
			if len(val) > 0 && val[0] == '"' {
				var err error
				val, err = strconv.Unquote(val)
				if err != nil {
					panic(err)
				}
			}

			r[key] = append(r[key], val)
		}
	}
	return Params(r)
}
开发者ID:nilium,项目名称:pinktxt,代码行数:25,代码来源:main.go

示例7: FieldsFunc

// FieldsFunc splits the string s at each run of Unicode code c satisfying f(c) and returns an array of slices of s.
// if all code points in s satisfy f(c) or the string is empty an empty slice is returned. FieldsFunc makes no guarantees
// about the order in which is calls f(c). if f does not return consistent results for given c FieldsFunc may crash
func FieldsFunc(s string, f func(rune) bool) []string {
	ft := func(c rune) bool {
		return !unicode.IsLetter(c) && !unicode.IsNumber(c)
	}

	fmt.Printf("Field are: %q", strings.FieldsFunc("  foo1;bar2*baz3...", ft)) // Fields are: ["foo1" "bar2" "baz3"]
	return strings.FieldsFunc(s, f)
}
开发者ID:upccup,项目名称:cuplearn,代码行数:11,代码来源:stringsTest.go

示例8: ImageLessBySemanticVersion

func ImageLessBySemanticVersion(a, b interface{}) bool {
	imageA, ok := a.(string)
	if !ok {
		return false
	}

	imageB, ok := b.(string)
	if !ok {
		return false
	}

	repoA, tagA, err := ParseDockerImage(imageA)
	if err != nil {
		return false
	}
	repoB, tagB, err := ParseDockerImage(imageB)
	if err != nil {
		return false
	}

	if repoA != repoB {
		return false
	}

	sep := func(c rune) bool { return c == '.' || c == ',' || c == '-' }
	min := func(a, b int) int {
		if a < b {
			return a
		} else {
			return b
		}
	}

	// compare the tags... we tokenize the tags by delimiters such as . and -
	fieldsA := strings.FieldsFunc(tagA, sep)
	fieldsB := strings.FieldsFunc(tagB, sep)
	for i := 0; i < min(len(fieldsA), len(fieldsB)); i++ {
		a, erra := strconv.Atoi(fieldsA[i])
		b, errb := strconv.Atoi(fieldsB[i])
		switch {
		case erra != nil && errb != nil:
			if fieldsA[i] == fieldsB[i] {
				continue
			} else {
				return fieldsA[i] < fieldsB[i]
			}
		case erra == nil && errb == nil:
			if a == b {
				continue
			} else {
				return a < b
			}
		case erra != nil || errb != nil:
			return false
		}
	}
	return false
}
开发者ID:conductant,项目名称:gohm,代码行数:58,代码来源:comparator.go

示例9: GetLastWord

func GetLastWord(linesrc string, off int) ([]string, []string) {

	wordsLeft := strings.FieldsFunc(linesrc[:off], func(r rune) bool {
		return !(unicode.IsLetter(r) || unicode.IsDigit(r))
	})

	wordsRight := strings.FieldsFunc(linesrc[off:], func(r rune) bool {
		return !(unicode.IsLetter(r) || unicode.IsDigit(r))
	})

	return wordsLeft, wordsRight
}
开发者ID:YouROK,项目名称:GoProjectManager,代码行数:12,代码来源:autocomplete.go

示例10: GetDestPlatforms

// interpret list of destination platforms (based on os & arch settings)
//0.5 add support for space delimiters (similar to BuildConstraints)
//0.5 add support for different oses/services
func GetDestPlatforms(specifiedOses string, specifiedArches string) []Platform {
	destOses := strings.FieldsFunc(specifiedOses, func(r rune) bool { return r == ',' || r == ' ' })
	destArchs := strings.FieldsFunc(specifiedArches, func(r rune) bool { return r == ',' || r == ' ' })

	for _, o := range destOses {
		supported := false
		for _, supportedPlatformArr := range getSupportedPlatforms() {
			supportedOs := supportedPlatformArr.Os
			if o == supportedOs {
				supported = true
			}
		}
		if !supported {
			log.Printf("WARNING: Operating System '%s' is unsupported", o)
		}
	}
	for _, o := range destArchs {
		supported := false
		for _, supportedPlatformArr := range getSupportedPlatforms() {
			supportedArch := supportedPlatformArr.Arch
			if o == supportedArch {
				supported = true
			}
		}
		if !supported {
			log.Printf("WARNING: Architecture '%s' is unsupported", o)
		}
	}
	if len(destOses) == 0 {
		destOses = []string{""}
	}
	if len(destArchs) == 0 {
		destArchs = []string{""}
	}
	var destPlatforms []Platform
	for _, supportedPlatformArr := range getSupportedPlatforms() {
		supportedOs := supportedPlatformArr.Os
		supportedArch := supportedPlatformArr.Arch
		for _, destOs := range destOses {
			if destOs == "" || supportedOs == destOs {
				for _, destArch := range destArchs {
					if destArch == "" || supportedArch == destArch {
						destPlatforms = append(destPlatforms, supportedPlatformArr)
					}
				}
			}
		}
	}
	if len(destPlatforms) < 1 {
		log.Printf("WARNING: no valid platforms specified")
	}
	return destPlatforms
}
开发者ID:kc87654321,项目名称:goxc,代码行数:56,代码来源:platforms.go

示例11: Parse

// Parse parses rules expressions
func (r *Rules) Parse(expression string) (*mux.Route, error) {
	functions := map[string]interface{}{
		"Host":            r.host,
		"HostRegexp":      r.hostRegexp,
		"Path":            r.path,
		"PathStrip":       r.pathStrip,
		"PathPrefix":      r.pathPrefix,
		"PathPrefixStrip": r.pathPrefixStrip,
		"Method":          r.methods,
		"Headers":         r.headers,
		"HeadersRegexp":   r.headersRegexp,
	}
	f := func(c rune) bool {
		return c == ':'
	}
	// get function
	parsedFunctions := strings.FieldsFunc(expression, f)
	if len(parsedFunctions) == 0 {
		return nil, errors.New("Error parsing rule: " + expression)
	}
	parsedFunction, ok := functions[parsedFunctions[0]]
	if !ok {
		return nil, errors.New("Error parsing rule: " + expression + ". Unknow function: " + parsedFunctions[0])
	}
	parsedFunctions = append(parsedFunctions[:0], parsedFunctions[1:]...)
	fargs := func(c rune) bool {
		return c == ',' || c == ';'
	}
	// get function
	parsedArgs := strings.FieldsFunc(strings.Join(parsedFunctions, ":"), fargs)
	if len(parsedArgs) == 0 {
		return nil, errors.New("Error parsing args from rule: " + expression)
	}

	inputs := make([]reflect.Value, len(parsedArgs))
	for i := range parsedArgs {
		inputs[i] = reflect.ValueOf(parsedArgs[i])
	}
	method := reflect.ValueOf(parsedFunction)
	if method.IsValid() {
		resultRoute := method.Call(inputs)[0].Interface().(*mux.Route)
		if r.err != nil {
			return nil, r.err
		}
		if resultRoute.GetError() != nil {
			return nil, resultRoute.GetError()
		}
		return resultRoute, nil
	}
	return nil, errors.New("Method not found: " + parsedFunctions[0])
}
开发者ID:goguardian,项目名称:traefik,代码行数:52,代码来源:rules.go

示例12: node_style_to_attribute

func node_style_to_attribute(n *html.Node) {
	style := node_get_attribute(n, "style")
	lines := strings.FieldsFunc(style, func(r rune) bool {
		return strings.ContainsRune(";\n", r)
	})
	for _, line := range lines {
		fields := strings.FieldsFunc(line, func(r rune) bool {
			return strings.ContainsRune(": ", r)
		})
		if len(fields) == 2 {
			node_set_attribute(n, fields[0], fields[1])
		}
	}
}
开发者ID:heartszhang,项目名称:famous,代码行数:14,代码来源:util.go

示例13: rquery

// Recursively query a decoded json blob
func rquery(blob interface{}, s ...string) (interface{}, error) {
	var (
		val interface{}
		err error
	)

	// If there is only a single string argument and if that single string argument has either a "." or a "[" in it
	// the assume it is a path specification and disagregate it into an array of indexes.
	terms := s
	if len(s) == 1 && strings.IndexAny(s[0], ".[]") != -1 {
		terms = strings.FieldsFunc(s[0], func(c rune) bool {
			return c == '.' || c == '[' || c == ']'
		})
	}
	val = blob
	for _, q := range terms {
		val, err = query(val, q)
		if err != nil {
			return nil, err
		}
	}
	switch val.(type) {
	case nil:
		return nil, fmt.Errorf("Nil value found at %s\n", s[len(s)-1])
	}
	return val, nil
}
开发者ID:davidkbainbridge,项目名称:jsonq,代码行数:28,代码来源:jsonq.go

示例14: ReadRow

//  Attempt to read up to a new line, skipping any comment lines found in
//  the process. Return a Row object containing the fields read and any
//  error encountered.
func (csvr *Reader) ReadRow() Row {
	var (
		r    Row
		line string
	)
	// Read lines until a non-comment line is found.
	for true {
		if line, r.Error = csvr.readLine(); r.Error != nil {
			return r
		}
		csvr.lineNum++
		if !csvr.Comments {
			break
		} else if !csvr.LooksLikeComment(line) {
			break
		} else if csvr.pastHeader && !csvr.CommentsInBody {
			break
		}
	}
	csvr.pastHeader = true

	// Break the line up into fields.
	r.Fields = strings.FieldsFunc(line, func(c rune) bool { return csvr.IsSep(c) })

	// Trim any unwanted characters.
	if csvr.Trim {
		for i := 0; i < len(r.Fields); i++ {
			r.Fields[i] = strings.Trim(r.Fields[i], csvr.Cutset)
		}
	}
	return r
}
开发者ID:taruti,项目名称:csvutil,代码行数:35,代码来源:reader.go

示例15: Args

func Args(s string) (result []string) {

	defer func() {
		if recover() != nil {
			result = make([]string, 0, 0)
		}
	}()

	inStr := false
	escape := false
	return strings.FieldsFunc(s, func(r rune) bool {
		if escape {
			escape = false
			return false
		}
		switch r {
		case '\\':
			escape = true
			return false
		case ' ', '\n', '\t':
			return !inStr
		case '"':
			inStr = !inStr
			return true
		default:
			return false
		}
	})
}
开发者ID:ylmbtm,项目名称:nitori-go,代码行数:29,代码来源:util.go


注:本文中的strings.FieldsFunc函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。