當前位置: 首頁>>代碼示例>>Golang>>正文


Golang regexp.Match函數代碼示例

本文整理匯總了Golang中regexp.Match函數的典型用法代碼示例。如果您正苦於以下問題:Golang Match函數的具體用法?Golang Match怎麽用?Golang Match使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Match函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: instructionParser

/**
 * Manage instruction from client
 *
 * @param client - Client object
 * @param buffer - Client input
 */
func instructionParser(client *Client, buffer []byte) bool {
	if matched, _ := regexp.Match("^/(quit|exit)$", buffer); matched { // Logout Instruction
		client.Close()
		return true
	} else if matched, _ := regexp.Match("^/cmd (.+)", buffer); matched { // Command Instruction
		r := regexp.MustCompile(`^/cmd (?P<command>.*)`)
		matches := r.FindStringSubmatch(string(buffer))
		if 1 < len(matches) {
			// Handle error if running failed
			defer func() {
				if err := recover(); err != nil {
					// Handle our error.
					fmt.Printf("[%s] Unable to execute command, error : %s\n", client.GetId(), err)
					client.SendMessage(fmt.Sprintf("Unable to execute the command, error : %s\n", err))
				}
			}()

			command := matches[1]
			fmt.Printf("[%s] Execute the following system command : %s\n", client.GetId(), command)
			output := cli.ExecShellScriptOrPanic(command)
			client.SendMessage(output)
		}

		// client.SendMessage();
	}

	return false
}
開發者ID:pilebones,項目名稱:backdoorGolang,代碼行數:34,代碼來源:server.go

示例2: verify_health_z

func verify_health_z(host string, registry *Registry, c *C) {
	var req *http.Request
	var resp *http.Response
	var err error
	path := "/healthz"

	req, _ = http.NewRequest("GET", "http://"+host+path, nil)
	bytes := verify_success(req, c)
	match, _ := regexp.Match("ok", bytes)
	c.Check(err, IsNil)
	c.Check(match, Equals, true)

	// Check that healthz does not reply during deadlock
	registry.Lock()
	defer registry.Unlock()

	httpClient := http.Client{
		Transport: &http.Transport{
			Dial: timeoutDialler(),
		},
	}

	req, err = http.NewRequest("GET", "http://"+host+path, nil)
	resp, err = httpClient.Do(req)

	c.Assert(err, Not(IsNil))
	match, _ = regexp.Match("i/o timeout", []byte(err.Error()))
	c.Assert(match, Equals, true)
	c.Check(resp, IsNil)

}
開發者ID:ndzj081221130,項目名稱:router-src,代碼行數:31,代碼來源:router_test.go

示例3: main

func main() {
	var (
		matched bool
		err     error
	)
	s := "300x300+0-10"
	if matched, err = regexp.MatchString(`[0-9]+[x][0-9]+[+][0-9]+[+][0-9]+`, s); matched {
		fmt.Println("1")
	} else if matched, err = regexp.MatchString(`[0-9]+[x][0-9]+[+][0-9]+[-][0-9]+`, s); matched {
		fmt.Println("2")
	} else if matched, err = regexp.MatchString(`[0-9]+[x][0-9]+[-][0-9]+[-][0-9]+`, s); matched {
		fmt.Println("3")
	} else if matched, err = regexp.MatchString(`[0-9]+[x][0-9]+[-][0-9]+[+][0-9]+`, s); matched {
		fmt.Println("4")
	} else {
		fmt.Println(err)
	}

	/*reg := regexp.MustCompile(`[0-9]+`)
	fmt.Println(reg.Find("500x500+12+13"))*/

	matched, err = regexp.Match("^faceCrop/[0-9]+[x][0-9]+", []byte("faceCrop/50f0x500"))
	fmt.Println("------", matched, err)

	fmt.Println("-------------------------")
	matched, _ = regexp.Match("^animated/(gif2webp|webp2gif)^", []byte("animated/gif2webp"))
	if !matched {
		log.Println("parameters dismatched")
	}
}
開發者ID:needkane,項目名稱:qiniu,代碼行數:30,代碼來源:regex.go

示例4: ParseFile

func ParseFile(filename string) (status []map[string]string, err error) {
	statusFile, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	lines := bytes.Split(statusFile, []byte("\n"))
	var fullStack []map[string]string
	currentStack := make(map[string]string)
	for _, l := range lines {
		if comment, _ := regexp.Match("^#", l); !comment {
			if matched, _ := regexp.Match("({|})", l); matched == true {
				if currentStack != nil {
					fullStack = append(fullStack, currentStack)
					currentStack = make(map[string]string)
				}
			} else {
				trimmed := bytes.Trim(l, " ")
				if len(trimmed) > 0 {
					vals := bytes.SplitN(trimmed, []byte("="), 2)
					if len(vals) > 0 {
						currentStack[string(vals[0])] = string(vals[1])
					}
				}
			}
		}
	}
	if currentStack != nil {
		fullStack = append(fullStack, currentStack)
	}
	return fullStack, nil
}
開發者ID:paperlesspost,項目名稱:nachos,代碼行數:31,代碼來源:parser.go

示例5: main

func main() {

	file, _ := os.Getwd()

	fmt.Println("glivesvr>>>Glive Server running...")
	e := log.NewLogger(1*log.MB, "/Users/Yate/DevEnv/logs/glive.log")
	if e != nil {
		fmt.Println(e.Error())
		os.Exit(0)
	}

	conf := flag.String("-f", file+"/example.conf", "server config file")
	flag.Parse()
	if *conf == "" {
		println("not has -f paramter")
		os.Exit(0)
	}
	f, e := os.Open(*conf)
	if e != nil {
		println(e.Error())
		os.Exit(0)
	}
	defer f.Close()

	fmt.Println("glivesvr>>>config file reading...")
	paramter := make(map[string]string)
	r := bufio.NewReader(f)
	for v, _, e := r.ReadLine(); e == nil; v, _, e = r.ReadLine() {
		if m, _ := regexp.Match("^#.*", v); m {

		} else if m, _ := regexp.Match(".*=.*", v); m {
			s := string(v)
			if n := strings.Index(s, "="); n != -1 {
				paramter[s[:n]] = s[n+1:]
			}
		}
	}

	p := ":" + paramter["port"]
	add, e := net.ResolveTCPAddr("tcp", p)
	if e != nil {
		log.Error(e.Error())
	}

	mgr := session.ConnMgr{Ob: &session.Observer{Ch: make(chan int)}, Sessions: make(map[int64]*session.Client)}
	go listener(&mgr, add)

	for {
		switch <-mgr.Ob.Ch {
		case 1:
			os.Exit(0)
		default:
			os.Exit(0)
		}
	}
}
開發者ID:yangting,項目名稱:glivesvr,代碼行數:56,代碼來源:glivesvr.go

示例6: listEntries

func listEntries() []Entry {
	fileinfos, err := ioutil.ReadDir("content")
	if err != nil {
		log.Fatal(err)
	}

	var entries []Entry
	var entry Entry

	for i, fileinfo := range fileinfos {
		name := filenameWithoutExtension(fileinfo.Name())
		if entry.Name != "" && entry.Name != name {
			entries = append(entries, entry)
			entry = Entry{}
		}
		entry.Name = name

		mimeType := mime.TypeByExtension(path.Ext(fileinfo.Name()))
		isImage := strings.HasPrefix(mimeType, "image")
		isVideo := strings.HasPrefix(mimeType, "video")
		isText := strings.HasPrefix(mimeType, "text")

		filename := "content/" + fileinfo.Name()
		if isImage {
			entry.Image = filename
		} else if isVideo {
			entry.Video = filename
		} else if isText && fileinfo.Size() <= 2000 {
			if entry.Video, err = readURLFromFile(filename); err != nil {
				continue
			}
			if entry.IsYoutube, err = regexp.Match(`.*youtube\.com\/.+`, []byte(entry.Video)); err != nil {
				continue
			} else if !entry.IsYoutube {
				if entry.IsVimeo, err = regexp.Match(`.*vimeo\.com\/.+`, []byte(entry.Video)); err != nil {
					continue
				}
			} else if !entry.IsYoutube && !entry.IsVimeo {
				continue
			}
		} else {
			continue
		}

		// It's the last file so just append the current entry
		if i == len(fileinfos)-1 {
			entries = append(entries, entry)
		}
	}

	return entries
}
開發者ID:bbh-labs,項目名稱:digitaldigest,代碼行數:52,代碼來源:entry.go

示例7: parse

func parse(b []byte) *Message {
	var servername, nick, user, host string
	var command, target, msg string
	words := bytes.Split(b, bytes.NewBufferString(" ").Bytes())

	if len(words) >= 4 {
		if match, _ := regexp.Match("^:", words[0]); match {
			if match, _ := regexp.Match("!|@", words[0]); match {
				i := 1
				for words[0][i] != '!' {
					i++
				}
				nick = bytes.NewBuffer(words[0][1:i]).String()
				j := i + 1
				for words[0][j] != '@' {
					j++
				}
				var wordstart int = i + 1
				if words[0][i+1] == '~' {
					wordstart = i + 2
				}

				user = bytes.NewBuffer(words[0][wordstart:j]).String()
				k := j + 1
				host = bytes.NewBuffer(words[0][k:len(words[0])]).String()
			} else {
				servername = bytes.NewBuffer(words[0][1:len(words[0])]).String()
			}
		}
		command = bytes.NewBuffer(words[1]).String()
		target = bytes.NewBuffer(words[2]).String()
		str := bytes.Join(words[3:len(words)], bytes.NewBufferString(" ").Bytes())
		msg = bytes.NewBuffer(str[1:len(str)]).String()
	} else {
		if match, _ := regexp.Match("PING", words[0]); match {
			command = "PING"
			host = bytes.NewBuffer(words[1][1:len(words[1])]).String()
			fmt.Println(host)
		}
	}

	return &Message{
		Servername: servername,
		Nickname:   nick,
		Username:   user,
		Hostname:   host,
		Command:    command,
		Target:     target,
		Message:    msg,
	}
}
開發者ID:Autumn,項目名稱:irc.go,代碼行數:51,代碼來源:irc.go

示例8: likeOrUnlike

func (self *Tester) likeOrUnlike(wantLike bool, have, want interface{}, description ...interface{}) bool {
	test := newTest("Like", have, want, description)
	if !wantLike {
		test.kind = "Unlike"
	}
	didPass := false
	switch want0 := want.(type) {
	case string:
		haveString := stringValue(have)
		didPass, error := regexp.Match(want0, []byte(haveString))
		if !wantLike {
			didPass = !didPass
		}
		if error != nil {
			panic("regexp.Match(" + want0 + ", ...): " + error.Error())
		}
		want = fmt.Sprintf("(?:%v)", want) // Make it look like a regular expression
		return self.hadResult(didPass, test, func() {
			self.Log(self.failMessageForMatch(test, stringValue(have), stringValue(want), wantLike))
		})
	}
	didPass, operator := compare(have, "{}~ ==", want)
	if !wantLike {
		didPass = !didPass
	}
	test.operator = operator
	return self.hadResult(didPass, test, func() {
		self.Log(self.failMessageForLike(test, stringValue(have), stringValue(want), wantLike))
	})
}
開發者ID:henrylee2cn,項目名稱:godocdown,代碼行數:30,代碼來源:terst.go

示例9: main

func main() {
	byte_src, str_src := []byte("rahul kumar"), "rahul kumar"

	match, _ := regexp.Match(`\w+\s+\w+`, byte_src)
	fmt.Println(match)

	match, _ = regexp.MatchString(`\w+\s+\w+`, str_src)
	fmt.Println(match)

	r := regexp.MustCompile(`(\w+)\s+(\w+)`)
	byte_tmpl, str_tmpl := []byte("$2, $1"), "$2, $1"
	dst := []byte("Nice to meet you. ")

	fmt.Printf("%s\n", r.Expand(dst, byte_tmpl, byte_src, r.FindSubmatchIndex(byte_src)))
	fmt.Printf("%s\n", r.ExpandString(dst, str_tmpl, str_src, r.FindStringSubmatchIndex(str_src)))

	r = regexp.MustCompile(`(\w+)`)
	fmt.Printf("%s\n", r.Find(byte_src))
	fmt.Printf("%s\n", r.FindAll(byte_src, -1))
	fmt.Printf("%v\n", r.FindAllIndex(byte_src, -1))
	fmt.Printf("%s\n", r.FindAllString(str_src, -1))
	fmt.Printf("%v\n", r.FindAllStringIndex(str_src, -1))
	fmt.Printf("%s\n", r.FindStringSubmatch(str_src))
	fmt.Printf("%s\n", r.FindAllStringSubmatch(str_src, -1))
	fmt.Printf("%v\n", r.FindAllStringSubmatchIndex(str_src, -1))
}
開發者ID:Bobberino,項目名稱:musings,代碼行數:26,代碼來源:regex_musings.go

示例10: TestLogEntryWritten

// Tests that writing to a tempfile log works.
// Matches the 'msg' of the output and deletes the tempfile.
func TestLogEntryWritten(t *testing.T) {
	log := logrus.New()
	// The colors were messing with the regexp so I turned them off.
	log.Formatter = &logrus.TextFormatter{DisableColors: true}
	tmpfile, err := ioutil.TempFile("", "test_lfshook")
	if err != nil {
		t.Errorf("Unable to generate logfile due to err: %s", err)
	}
	fname := tmpfile.Name()
	defer func() {
		tmpfile.Close()
		os.Remove(fname)
	}()
	hook := NewHook(PathMap{
		logrus.InfoLevel: fname,
	})
	log.Hooks.Add(hook)

	log.Info(expectedMsg)

	if contents, err := ioutil.ReadAll(tmpfile); err != nil {
		t.Errorf("Error while reading from tmpfile: %s", err)
	} else if matched, err := regexp.Match("msg=\""+expectedMsg+"\"", contents); err != nil || !matched {
		t.Errorf("Message read (%s) doesnt match message written (%s) for file: %s", contents, expectedMsg, fname)
	}
}
開發者ID:marconi,項目名稱:lfshook,代碼行數:28,代碼來源:lfshook_test.go

示例11: TestScriptPath

func TestScriptPath(t *testing.T) {
	cases := []struct {
		Input   string
		Pattern string
	}{
		{
			"/tmp/script.sh",
			`^/tmp/script\.sh$`,
		},
		{
			"/tmp/script_%RAND%.sh",
			`^/tmp/script_(\d+)\.sh$`,
		},
	}

	for _, tc := range cases {
		comm := &Communicator{connInfo: &connectionInfo{ScriptPath: tc.Input}}
		output := comm.ScriptPath()

		match, err := regexp.Match(tc.Pattern, []byte(output))
		if err != nil {
			t.Fatalf("bad: %s\n\nerr: %s", tc.Input, err)
		}
		if !match {
			t.Fatalf("bad: %s\n\n%s", tc.Input, output)
		}
	}
}
開發者ID:devendraPSL,項目名稱:terraform-api,代碼行數:28,代碼來源:communicator_test.go

示例12: parse

func (this *AudioMerger) parse(cmd string) (format string, mime string, bucket string, url string, duration string, err error) {
	pattern := "^amerge/format/[a-zA-Z0-9]+/mime/[0-9a-zA-Z-_=]+/bucket/[0-9a-zA-Z-_=]+/url/[0-9a-zA-Z-_=]+(/duration/(first|shortest|longest)){0,1}$"
	matched, _ := regexp.Match(pattern, []byte(cmd))
	if !matched {
		err = errors.New("invalid amerge command format")
		return
	}

	var decodeErr error
	format = getParam(cmd, "format/[a-zA-Z0-9]+", "format")
	mime, decodeErr = getParamDecoded(cmd, "mime/[0-9a-zA-Z-_=]+", "mime")
	if decodeErr != nil {
		err = errors.New("invalid amerge parameter 'mime'")
		return
	}
	bucket, decodeErr = getParamDecoded(cmd, "bucket/[0-9a-zA-Z-_=]+", "bucket")
	if decodeErr != nil {
		err = errors.New("invalid amerge parameter 'bucket'")
		return
	}
	url, decodeErr = getParamDecoded(cmd, "url/[0-9a-zA-Z-_=]+", "url")
	if decodeErr != nil {
		err = errors.New("invalid amerge parameter 'url'")
		return
	}
	duration = getParam(cmd, "duration/(first|shortest|longest)", "duration")
	if duration == "" {
		duration = "longest"
	}
	return
}
開發者ID:dulumao,項目名稱:qiniu-ufop-service,代碼行數:31,代碼來源:amerge.go

示例13: hostnameFromHTTPLocationHeader

// Performs http(s) request and parses possible 'Location' headers.
func hostnameFromHTTPLocationHeader(ip, protocol string, timeout int64) (string, error) {
	req, err := http.NewRequest("GET", protocol+"://"+ip, nil)
	if err != nil {
		return "", err
	}
	tr := &http.Transport{
		Dial: func(network, addr string) (net.Conn, error) {
			return net.DialTimeout(network, addr, time.Duration(timeout)*time.Millisecond)
		},
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	res, err := tr.RoundTrip(req)
	if err != nil {
		return "", err
	}
	location := res.Header["Location"]
	if location != nil {
		u, err := url.Parse(location[0])
		if err != nil {
			return "", err
		}
		host := u.Host
		if m, _ := regexp.Match("[a-zA-Z]+", []byte(host)); m == true {
			return host, nil
		}
		return "", fmt.Errorf("%v: unsuccessful header match", ip)
	}
	return "", fmt.Errorf("%v: unsuccessful header match", ip)
}
開發者ID:intfrr,項目名稱:blacksheepwall,代碼行數:30,代碼來源:header.go

示例14: DbTunnelAutoComplete

func DbTunnelAutoComplete(c *cli.Context) error {
	appName := CurrentAppCompletion(c)
	if appName == "" {
		return nil
	}

	lastArg := ""
	if len(os.Args) > 2 {
		lastArg = os.Args[len(os.Args)-2]
	}

	if !strings.HasPrefix(lastArg, "-") {
		client := config.ScalingoClient()
		variables, err := client.VariablesList(appName)
		if err == nil {

			for _, v := range variables {
				if matched, err := regexp.Match("SCALINGO_.*_URL", []byte(v.Name)); matched && err == nil {
					fmt.Println(v.Name)
				}
			}
		}
	}

	return nil
}
開發者ID:carriercomm,項目名稱:cli-8,代碼行數:26,代碼來源:db_tunnel.go

示例15: FileList

// 指定したディレクトリにあるpatternにマッチするファイルリストを取得する
func FileList(dir string, pattern string) ([]string, error) {
	files := []string{}

	if stat, err := os.Stat(dir); stat == nil || !stat.IsDir() {
		log.Println(dir + " is not directory")
		return files, err
	}

	infos, err := ioutil.ReadDir(dir)
	if err != nil {
		return files, nil
	}

	for _, info := range infos {
		name := info.Name()
		matched, err := regexp.Match(pattern, []byte(name))
		if err != nil {
			return files, err
		}
		if matched {
			files = append(files, name)
		}
	}

	return files, nil
}
開發者ID:uwork,項目名稱:gorond,代碼行數:27,代碼來源:util.go


注:本文中的regexp.Match函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。