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


Golang Regexp.Match方法代码示例

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


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

示例1: grep

func grep(re *regexp.Regexp, path string, r io.Reader) error {
	in := bufio.NewReader(r)
	lineNo := 0
	for {
		switch line, prefix, err := in.ReadLine(); {
		case prefix:
			return errors.New("Line is too long")
		case err == io.EOF:
			return nil
		case err != nil:
			return err
		default:
			lineNo++
			match := re.Match(line)
			if (match && !*vFlag) || (!match && *vFlag) {
				if *nFlag && path != "" {
					os.Stdout.WriteString(path + ":")
				}
				if *nFlag {
					fmt.Print(lineNo, ":")
				}
				os.Stdout.WriteString(string(line) + "\n")
			}
		}
	}
	panic("Unreachable")
}
开发者ID:vivounicorn,项目名称:eaburns.cmds,代码行数:27,代码来源:main.go

示例2: 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

示例3: grep

func grep(rx *regexp.Regexp, r io.Reader) bool {
	matched := false
	s := bufio.NewScanner(r)
	for {
		if !s.Scan() {
			break
		}
		b := s.Bytes()

		m := rx.Match(b)
		if invert && !m {
			matched = true
			if _, err := os.Stdout.Write(b); err != nil {
				fmt.Println(err.Error())
				os.Exit(1)
			}
			if _, err := fmt.Fprintln(os.Stdout); err != nil {
				fmt.Println(err.Error())
				os.Exit(1)
			}
		} else if !invert && m {
			matched = true
			if _, err := os.Stdout.Write(b); err != nil {
				fmt.Println(err.Error())
				os.Exit(1)
			}
			if _, err := fmt.Fprintln(os.Stdout); err != nil {
				fmt.Println(err.Error())
				os.Exit(1)
			}
		}
	}
	return matched
}
开发者ID:akutz,项目名称:gnixutils,代码行数:34,代码来源:grep.go

示例4: LoadPages

// 载入所有Page
func LoadPages(root string, exclude string) (pages map[string]Mapper, err error) {
	pages = make(map[string]Mapper)
	err = nil
	var _exclude *regexp.Regexp
	if exclude != "" {
		_exclude, err = regexp.Compile(exclude)
		if err != nil {
			errMsg := fmt.Sprintf("BAD pages exclude regexp %q >> ", exclude, err.Error())
			err = errors.New(errMsg)
			return
		}
	}
	err = filepath.Walk(filepath.Join(root, "pages/"), func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if info.IsDir() || strings.HasPrefix(filepath.Base(path), ".") {
			return nil
		}
		if _exclude != nil && _exclude.Match([]byte(path[len(root+"pages/"):])) {
			return nil
		}
		page, err := LoadPage(root, path)
		if err != nil {
			return err
		}
		pages[page.Id()] = page
		return nil
	})
	return
}
开发者ID:newblue,项目名称:neyo,代码行数:32,代码来源:payload.go

示例5: read

func read(name string, wg *sync.WaitGroup, reg *regexp.Regexp) {
	defer wg.Done()
	f, err := os.Open(name)
	if err != nil {
		errlog.Println(err)
		return
	}
	defer f.Close()
	var r io.Reader
	ext := filepath.Ext(name)
	switch ext {
	case ".gz":
		r, err = gzip.NewReader(f)
		if err != nil {
			log.Println(err)
			return
		}
	case ".bz":
		r = bzip2.NewReader(f)
	default:
		errlog.Println("Unknown extension:", ext)
		return
	}
	scanner := bufio.NewScanner(r)
	for scanner.Scan() {
		b := scanner.Bytes()
		if reg.Match(b) {
			log.Printf("%s: %s", name, b)
		}
	}
	if err := scanner.Err(); err != nil {
		errlog.Printf("Error while reading %s: %s", name, err)
	}
}
开发者ID:natefinch,项目名称:pcgrep,代码行数:34,代码来源:main.go

示例6: LoadPosts

// 载入所有的Post
func LoadPosts(root string, exclude string) (posts map[string]Mapper, err error) {
	posts = make(map[string]Mapper)
	err = nil
	var _exclude *regexp.Regexp
	if exclude != "" {
		_exclude, err = regexp.Compile(exclude)
		if err != nil {
			err = errors.New("BAD pages exclude regexp : " + exclude + "\t" + err.Error())
			return
		}
	}
	err = filepath.Walk(root+"posts/", func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if info.IsDir() || strings.HasPrefix(filepath.Base(path), ".") {
			return nil
		}
		if _exclude != nil && _exclude.Match([]byte(path[len(root+"posts/"):])) {
			return nil
		}
		post, err := LoadPost(root, path)
		if err != nil {
			return err
		}
		posts[post.Id()] = post
		return nil
	})
	return
}
开发者ID:6wei,项目名称:gor,代码行数:31,代码来源:payload.go

示例7: applyRegExpFocus

func (collection *exampleCollection) applyRegExpFocus(focusFilter *regexp.Regexp) {
	for _, example := range collection.examples {
		if !focusFilter.Match([]byte(example.concatenatedString())) {
			example.skip()
		}
	}
}
开发者ID:nikai3d,项目名称:ginkgo,代码行数:7,代码来源:example_collection.go

示例8: ValidateCSVData

func ValidateCSVData(fn string, re *regexp.Regexp) (err error) {
	fin, err := os.Open(fn)
	if err != nil {
		// do not return the error, the file might be not needed
		return nil
	}
	defer fin.Close()
	r := bufio.NewReader(fin)
	line_number := 1
	for {
		line, truncated, err := r.ReadLine()
		if err != nil {
			break
		}
		if truncated {
			return errors.New("line too long")
		}
		// skip the header line
		if line_number > 1 {
			if !re.Match(line) {
				return errors.New(fmt.Sprintf("%s: error on line %d: %s", fn, line_number, line))
			}
		}
		line_number++
	}
	return
}
开发者ID:intralanman,项目名称:cgrates,代码行数:27,代码来源:loader_helpers.go

示例9: findRecursively

// find the directories and files which matches the regular expression
func findRecursively(dir *os.File, reg *regexp.Regexp, currentwd string) (dirs, files []string) {
	dirs = make([]string, 0)
	files = make([]string, 0)

	fileInfos, err := dir.Readdir(0)
	if err != nil {
		return
	}
	for i := 0; i < len(fileInfos); i++ {
		name := fileInfos[i].Name()
		if reg.Match([]byte(name)) == true {
			if fileInfos[i].IsDir() == true {
				dirs = append(dirs, currentwd+"/"+name)
			} else {
				files = append(dirs, currentwd+"/"+name)
			}
		}
		if fileInfos[i].IsDir() == true {
			redir, err := os.Open(currentwd + "/" + name)
			if err != nil {
				continue
			}
			newDirs, newFiles := findRecursively(redir, reg, currentwd+"/"+name)
			dirs = append(dirs, newDirs...)
			files = append(files, newFiles...)
			redir.Close()
		}
	}
	return
}
开发者ID:GarX,项目名称:go-pac,代码行数:31,代码来源:worker.go

示例10: ExpectRegex

func (expect *ExpectSubprocess) ExpectRegex(re *regexp.Regexp) (buf []byte, err error) {
	join := make([][]byte, 0, 1024)
	chunk := make([]byte, 255)
	line := make([]byte, 0, 1024)

	var n int
	for {
		n, err = expect.f.Read(chunk)
		if err != nil {
			return
		}

		for i := 0; i < n; i++ {
			if chunk[i] != '\n' {
				line = append(line, chunk[i])
			}
			success := re.Match(line)
			if success {
				buf = flatten(join)
				return
			}
			if chunk[i] == '\n' {
				line = append(line, chunk[i])
				join = append(join, line)
				line = make([]byte, 0, 1024)
			}
		}

	}
}
开发者ID:pombredanne,项目名称:goss,代码行数:30,代码来源:gexpect.go

示例11: shell

// Shell worker.
func shell(check *Check, name *string, sleep *time.Duration) {
	// Execute with shell in N attemps.
	var out []byte
	var err error
	for i := 0; i < check.Tries; {
		out, err = exec.Command("sh", "-c", check.Shell).CombinedOutput()
		if err == nil {
			if check.Match != "" { // Match regexp.
				var regex *regexp.Regexp
				regex, err = regexp.Compile(check.Match)
				if err == nil && !regex.Match(out) {
					err = errors.New("Expected:\n" + check.Match + "\n\nGot:\n" + string(out))
				}
			}
			break
		}
		i++
		if i < check.Tries {
			time.Sleep(*sleep)
		}
	}
	// Process results.
	if err == nil {
		if check.Failed {
			ts := time.Now()
			mutex.Lock()
			check.Failed = false
			check.Since = ts.Format(time.RFC3339)
			modified = etag(ts)
			mutex.Unlock()
			subject := "Fixed: " + *name
			log(5, subject)
			if check.Notify != "" {
				notify(check, &subject, nil)
			}
			if check.Alert != "" {
				alert(check, name, nil, false)
			}
		}
	} else {
		if !check.Failed {
			ts := time.Now()
			mutex.Lock()
			check.Failed = true
			check.Since = ts.Format(time.RFC3339)
			modified = etag(ts)
			mutex.Unlock()
			msg := string(out) + err.Error()
			subject := "Failed: " + *name
			log(5, subject+"\n"+msg)
			if check.Notify != "" {
				notify(check, &subject, &msg)
			}
			if check.Alert != "" {
				alert(check, name, &msg, true)
			}
		}
	}
}
开发者ID:chillum,项目名称:jsonmon,代码行数:60,代码来源:main.go

示例12: grepFailures

func grepFailures(revs []*Revision, re *regexp.Regexp) []*failure {
	return processFailureLogs(revs, func(build *Build, data []byte) []*failure {
		if !re.Match(data) {
			return nil
		}
		return []*failure{new(failure)}
	})
}
开发者ID:rsc,项目名称:go-misc,代码行数:8,代码来源:main.go

示例13: Find

// Find takes a compiled regexp and starting at the top of the file
// returns the line number of all lines that match.
func (traveler *FileTraveler) Find(rx *regexp.Regexp) (matches []int) {
	traveler.ForEach(func(pos int, line []byte) {
		if rx.Match(line) {
			matches = append(matches, pos)
		}
	})
	return
}
开发者ID:jmervine,项目名称:filetrav,代码行数:10,代码来源:filetrav.go

示例14: ConstraintRegexp

//ConstraintRegexp limits request item by regexp
func ConstraintRegexp(item string, reg *regexp.Regexp) func(map[string]string) bool {
	return func(m map[string]string) bool {
		if value, ok := m[item]; ok {
			return reg.Match([]byte(value))
		}
		return false
	}
}
开发者ID:hypertornado,项目名称:prago,代码行数:9,代码来源:router.go

示例15: ResponseMatchesGeneral

// ResponseMatchesGeneral is an abstraction of ResponseMatches and
// ResponseMatchesInsecure that simply varies in the security of the connection
func ResponseMatchesGeneral(urlstr string, re *regexp.Regexp, secure bool) (int, string, error) {
	body := chkutil.URLToBytes(urlstr, secure)
	if re.Match(body) {
		return errutil.Success()
	}
	msg := "Response didn't match regexp"
	return errutil.GenericError(msg, re.String(), []string{string(body)})
}
开发者ID:allenbhuiyan,项目名称:distributive,代码行数:10,代码来源:network.go


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