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


Golang regexp.Regexp类代码示例

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


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

示例1: testFindAllIndex

func testFindAllIndex(t *testing.T, tc *testCase, x *Index, rx *regexp.Regexp, n int) {
	res := x.FindAllIndex(rx, n)
	exp := rx.FindAllStringIndex(tc.source, n)

	// check that the lengths match
	if len(res) != len(exp) {
		t.Errorf("test %q, FindAllIndex %q (n = %d): expected %d results; got %d", tc.name, rx, n, len(exp), len(res))
	}

	// if n >= 0 the number of results is limited --- unless n >= all results,
	// we may obtain different positions from the Index and from regexp (because
	// Index may not find the results in the same order as regexp) => in general
	// we cannot simply check that the res and exp lists are equal

	// check that each result is in fact a correct match and the result is sorted
	for i, r := range res {
		if r[0] < 0 || r[0] > r[1] || len(tc.source) < r[1] {
			t.Errorf("test %q, FindAllIndex %q, result %d (n == %d): illegal match [%d, %d]", tc.name, rx, i, n, r[0], r[1])
		} else if !rx.MatchString(tc.source[r[0]:r[1]]) {
			t.Errorf("test %q, FindAllIndex %q, result %d (n = %d): [%d, %d] not a match", tc.name, rx, i, n, r[0], r[1])
		}
	}

	if n < 0 {
		// all results computed - sorted res and exp must be equal
		for i, r := range res {
			e := exp[i]
			if r[0] != e[0] || r[1] != e[1] {
				t.Errorf("test %q, FindAllIndex %q, result %d: expected match [%d, %d]; got [%d, %d]",
					tc.name, rx, i, e[0], e[1], r[0], r[1])
			}
		}
	}
}
开发者ID:IntegerCompany,项目名称:linaro-android-gcc,代码行数:34,代码来源:suffixarray_test.go

示例2: removeTimestampAndRequestIdFromLogLine

func removeTimestampAndRequestIdFromLogLine(line, requestId string, requestIdRegexp *regexp.Regexp) (string, bool) {
	sep := "\t"
	parts := strings.Split(line, sep)

	// assume timestamp is before request_id
	for i, p := range parts {
		if p == requestId {
			hasTimeStamp := i > 0 && timestampRegexp.MatchString(parts[i-1])
			if hasTimeStamp {
				parts = append(parts[:i-1], parts[i+1:]...)
			} else {
				parts = append(parts[:i], parts[i+1:]...)
			}
			return strings.Join(parts, sep), true
		}
	}

	//remove a log line from another request_id
	for _, p := range parts {
		if requestIdRegexp.MatchString(p) {
			return "", false
		}
	}
	return line, true
}
开发者ID:coopernurse,项目名称:lambda,代码行数:25,代码来源:util.go

示例3: list

// list is a subcommand to list up snippets.
// It just finds snippet files in the snippet directory and listed them.
func list(c *cli.Context) {
	var pattern *regexp.Regexp
	var err error
	query := c.Args().First()
	if len(query) > 0 {
		pattern, err = regexp.Compile(fmt.Sprintf(".*%s.*", query))
		if err != nil {
			log.Fatal(err)
		}
	}

	err = filepath.Walk(
		conf.SnippetDirectory,
		func(path string, info os.FileInfo, err error) error {
			if info.IsDir() {
				return nil
			}
			rel, err := filepath.Rel(conf.SnippetDirectory, path)

			if pattern != nil {
				if pattern.MatchString(rel) {
					fmt.Println(rel)
				}
				return nil
			}

			fmt.Println(rel)
			return nil
		},
	)

	if err != nil {
		log.Fatal(err)
	}
}
开发者ID:sudix,项目名称:chickenhead,代码行数:37,代码来源:main.go

示例4: checkAuth

func checkAuth(client <-chan string, result chan<- bool) {
	var (
		attempt int
		data    string

		pass *regexp.Regexp
	)

	pass = regexp.MustCompile(`^(?i)PASS(?-i) ` + opt.Password + `\r?\n?$`)

	attempt = 0
	for data = range client {
		if attempt > AuthAttempts {
			log.Print("Authentication bad, tearing down.")
			result <- false
			return
		}

		if pass.MatchString(data) {
			log.Print("Authentication good, open sesame.")
			result <- true
			return
		}

		attempt++
	}
}
开发者ID:kamaln7,项目名称:nbnc,代码行数:27,代码来源:auth.go

示例5: parseNetDevStats

func parseNetDevStats(r io.Reader, ignore *regexp.Regexp) (map[string]map[string]string, error) {
	scanner := bufio.NewScanner(r)
	scanner.Scan() // skip first header
	scanner.Scan()
	parts := strings.Split(string(scanner.Text()), "|")
	if len(parts) != 3 { // interface + receive + transmit
		return nil, fmt.Errorf("invalid header line in net/dev: %s",
			scanner.Text())
	}

	header := strings.Fields(parts[1])
	netDev := map[string]map[string]string{}
	for scanner.Scan() {
		line := strings.TrimLeft(string(scanner.Text()), " ")
		parts := procNetDevFieldSep.Split(line, -1)
		if len(parts) != 2*len(header)+1 {
			return nil, fmt.Errorf("invalid line in net/dev: %s", scanner.Text())
		}

		dev := parts[0][:len(parts[0])]
		if ignore.MatchString(dev) {
			log.Debugf("Ignoring device: %s", dev)
			continue
		}
		netDev[dev] = map[string]string{}
		for i, v := range header {
			netDev[dev]["receive_"+v] = parts[i+1]
			netDev[dev]["transmit_"+v] = parts[i+1+len(header)]
		}
	}
	return netDev, scanner.Err()
}
开发者ID:prometheus,项目名称:node_exporter,代码行数:32,代码来源:netdev_linux.go

示例6: NamedUrlValuesRegexpGroup

// match regexp with string, and return a named group map
// Example:
//   regexp: "(?P<name>[A-Za-z]+)-(?P<age>\\d+)"
//   string: "CGC-30"
//   return: map[string][]string{ "name":["CGC"], "age":["30"] }
func NamedUrlValuesRegexpGroup(str string, reg *regexp.Regexp) (ng url.Values, matched bool) {
	rst := reg.FindStringSubmatch(str)
	if len(rst) < 1 {
		return
	}
	//for i,s :=range rst{
	//	fmt.Printf("%d => %s\n",i,s)
	//}
	ng = url.Values{}
	lenRst := len(rst)
	sn := reg.SubexpNames()
	for k, v := range sn {
		// SubexpNames contain the none named group,
		// so must filter v == ""
		//fmt.Printf("%s => %s\n",k,v)
		if k == 0 || v == "" {
			continue
		}
		if k+1 > lenRst {
			break
		}
		ng.Add(v, rst[k])
	}
	matched = true
	return
}
开发者ID:xgene,项目名称:beego,代码行数:31,代码来源:router.go

示例7: GetDeps

func GetDeps(data []byte, dependRegex *regexp.Regexp) []string {
	var deps = []string{}
	for _, m := range dependRegex.FindAllStringSubmatch(string(data), -1) {
		deps = append(deps, m[regexFilepathGroupIndex])
	}
	return deps
}
开发者ID:buildfx,项目名称:build.fx,代码行数:7,代码来源:buildfx.go

示例8: TestMatchResourceAttr

func TestMatchResourceAttr(name, key string, r *regexp.Regexp) TestCheckFunc {
	return func(s *terraform.State) error {
		ms := s.RootModule()
		rs, ok := ms.Resources[name]
		if !ok {
			return fmt.Errorf("Not found: %s", name)
		}

		is := rs.Primary
		if is == nil {
			return fmt.Errorf("No primary instance: %s", name)
		}

		if !r.MatchString(is.Attributes[key]) {
			return fmt.Errorf(
				"%s: Attribute '%s' didn't match %q, got %#v",
				name,
				key,
				r.String(),
				is.Attributes[key])
		}

		return nil
	}
}
开发者ID:monkeylittleinc,项目名称:terraform,代码行数:25,代码来源:testing.go

示例9: getNetDevStats

func getNetDevStats(ignore *regexp.Regexp) (map[string]map[string]string, error) {
	netDev := map[string]map[string]string{}

	var ifap, ifa *C.struct_ifaddrs
	if C.getifaddrs(&ifap) == -1 {
		return nil, errors.New("getifaddrs() failed")
	}
	defer C.freeifaddrs(ifap)

	for ifa = ifap; ifa != nil; ifa = ifa.ifa_next {
		if ifa.ifa_addr.sa_family == C.AF_LINK {
			dev := C.GoString(ifa.ifa_name)
			if ignore.MatchString(dev) {
				log.Debugf("Ignoring device: %s", dev)
				continue
			}

			devStats := map[string]string{}
			data := (*C.struct_if_data)(ifa.ifa_data)

			devStats["receive_packets"] = strconv.Itoa(int(data.ifi_ipackets))
			devStats["transmit_packets"] = strconv.Itoa(int(data.ifi_opackets))
			devStats["receive_errs"] = strconv.Itoa(int(data.ifi_ierrors))
			devStats["transmit_errs"] = strconv.Itoa(int(data.ifi_oerrors))
			devStats["receive_bytes"] = strconv.Itoa(int(data.ifi_ibytes))
			devStats["transmit_bytes"] = strconv.Itoa(int(data.ifi_obytes))
			devStats["receive_multicast"] = strconv.Itoa(int(data.ifi_imcasts))
			devStats["transmit_multicast"] = strconv.Itoa(int(data.ifi_omcasts))
			devStats["receive_drop"] = strconv.Itoa(int(data.ifi_iqdrops))
			netDev[dev] = devStats
		}
	}

	return netDev, nil
}
开发者ID:juergenhoetzel,项目名称:node_exporter,代码行数:35,代码来源:netdev_openbsd.go

示例10: ReaderWaitFor

func ReaderWaitFor(r io.Reader, re *regexp.Regexp, duration time.Duration) ([]byte, bool, error) {
	res := make(chan *readWaitResult, 1)
	quit := make(chan bool, 1)
	go func() {
		out := &bytes.Buffer{}
		var err error
		found := false
		var n int
		buf := make([]byte, 1024)
		for err == nil && !found {
			select {
			case <-quit:
				break
			default:
				n, err = r.Read(buf)
				if n > 0 {
					out.Write(buf[0:n])
				}
				found = re.Match(out.Bytes())
			}
		}
		res <- &readWaitResult{out.Bytes(), found, err}
	}()
	select {
	case result := <-res:
		return result.byts, result.found, result.err
	case <-time.After(duration):
		quit <- true
		return nil, false, ErrTimeout
	}
}
开发者ID:cretz,项目名称:systrument,代码行数:31,代码来源:io.go

示例11: checkNewChapter

func checkNewChapter(re *regexp.Regexp, l []byte) (depth int, title string) {
	if m := re.FindSubmatch(l); m != nil && m[1][0] == m[3][0] {
		depth = int(m[1][0] - '0')
		title = string(m[2])
	}
	return
}
开发者ID:haifengwang,项目名称:makeepub,代码行数:7,代码来源:make.go

示例12: processColorTemplates

func processColorTemplates(colorTemplateRegexp *regexp.Regexp, buf []byte) []byte {
	// We really want ReplaceAllSubmatchFunc, i.e.: https://github.com/golang/go/issues/5690
	// Instead we call FindSubmatch on each match, which means that backtracking may not be
	// used in custom Regexps (matches must also match on themselves without context).
	colorTemplateReplacer := func(token []byte) []byte {
		tmp2 := []byte{}
		groups := colorTemplateRegexp.FindSubmatch(token)
		var ansiActive ActiveAnsiCodes
		for _, codeBytes := range bytes.Split(groups[1], bytesComma) {
			colorCode, ok := ansiColorCodes[string(codeBytes)]
			if !ok {
				// Don't modify the text if we don't recognize any of the codes
				return groups[0]
			}
			for _, code := range colorCode.GetAnsiCodes() {
				ansiActive.add(code)
				tmp2 = append(tmp2, ansiEscapeBytes(code)...)
			}
		}
		if len(groups[2]) > 0 {
			tmp2 = append(tmp2, groups[3]...)
			tmp2 = append(tmp2, ansiActive.getResetBytes()...)
		}
		return tmp2
	}
	return colorTemplateRegexp.ReplaceAllFunc(buf, colorTemplateReplacer)
}
开发者ID:tillberg,项目名称:ansi-log,代码行数:27,代码来源:log.go

示例13: readFile

func (r *SSHConfigReader) readFile(c SSHConfig, re *regexp.Regexp, f string) error {
	file, err := os.Open(f)
	if err != nil {
		return err
	}
	defer file.Close()

	hosts := []string{"*"}
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		match := re.FindStringSubmatch(line)
		if match == nil {
			continue
		}

		names := strings.Fields(match[2])
		if strings.EqualFold(match[1], "host") {
			hosts = names
		} else {
			for _, host := range hosts {
				for _, name := range names {
					c[host] = name
				}
			}
		}
	}

	return scanner.Err()
}
开发者ID:thotanagaraju,项目名称:hub,代码行数:30,代码来源:ssh_config.go

示例14: genericSplit

// genericSplit provides a generic version of Split and SplitAfter.
// Set the includeSep bool to true to have it include the separtor.
func genericSplit(re *regexp.Regexp, s string, numFields int, includeSep bool) []string {
	if numFields == 0 {
		return make([]string, 0)
	}

	// Using regexp, including the separator is really easy. Instead of
	// including up to the start of the separator we include to the end.
	// The start of the separator is stored in index 0.
	// The end of the separator is stored in index 1.
	var includeTo int
	if includeSep {
		includeTo = 1
	} else {
		includeTo = 0
	}

	count := re.FindAllStringIndex(s, numFields-1)
	n := len(count) + 1
	stor := make([]string, n)

	if n == 1 {
		stor[0] = s
		return stor
	}

	stor[0] = s[:count[0][includeTo]]

	for i := 1; i < n-1; i++ {
		stor[i] = s[count[i-1][1]:count[i][includeTo]]
	}

	stor[n-1] = s[count[n-2][1]:]

	return stor
}
开发者ID:humbhenri,项目名称:sudoku.go,代码行数:37,代码来源:sudoku.go

示例15: stripLiteral

// strip text between given markers
func stripLiteral(wikitext []byte, start *regexp.Regexp, end *regexp.Regexp) (out []byte) {
	var loc []int

	out = make([]byte, 0, len(wikitext))

top:
	loc = start.FindIndex(wikitext)
	if loc != nil { // match?
		goto strip
	}
	out = append(out, wikitext...) // add what's left
	return
strip:
	out = append(out, wikitext[:loc[0]]...)
	wikitext = wikitext[loc[1]:]
	loc = end.FindIndex(wikitext)
	if loc != nil { // match?
		goto endstrip
	}
	return // assume end at EOF if no match
endstrip:
	wikitext = wikitext[loc[1]:]
	goto top

	panic("unreachable") // please the compiler
}
开发者ID:andlabs,项目名称:segaret_scans,代码行数:27,代码来源:stripwiki.go


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