本文整理汇总了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")
}
示例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
}
}
示例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
}
示例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
}
示例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)
}
}
示例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
}
示例7: applyRegExpFocus
func (collection *exampleCollection) applyRegExpFocus(focusFilter *regexp.Regexp) {
for _, example := range collection.examples {
if !focusFilter.Match([]byte(example.concatenatedString())) {
example.skip()
}
}
}
示例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
}
示例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
}
示例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)
}
}
}
}
示例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)
}
}
}
}
示例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)}
})
}
示例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
}
示例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
}
}
示例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)})
}