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


Golang regexp.MustCompile函数代码示例

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


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

示例1: validateCmdArgs

func validateCmdArgs(cmd *commander.Command, args []string) error {
	mustVal := 0
	optionVal := 0
	must := regexp.MustCompile(`<\w+>`)
	option := regexp.MustCompile(`\[\w+\]`)

	for _, action := range strings.Split(cmd.UsageLine, " ") {
		if must.MatchString(action) {
			mustVal++
		}
		if option.MatchString(action) {
			optionVal++
		}
		// skip arguments validation
		if action == "..." {
			if mustVal <= len(args) {
				return nil
			}
		}
	}
	if mustVal <= len(args) && len(args) <= mustVal+optionVal {
		return nil
	}
	return errors.New("invalid argument\nUsage: " + cmd.UsageLine)
}
开发者ID:uzulla,项目名称:go-vultr,代码行数:25,代码来源:command.go

示例2: filterStriptags

func filterStriptags(value interface{}, args []interface{}, ctx *FilterChainContext) (interface{}, error) {
	str, is_str := value.(string)
	if !is_str {
		return nil, errors.New(fmt.Sprintf("%v is not of type string", value))
	}

	if len(args) > 1 {
		return nil, errors.New("Please provide a comma-seperated string with tags (or no string to remove all tags).")
	}

	if len(args) == 1 {
		taglist, is_string := args[0].(string)
		if !is_string {
			return nil, errors.New(fmt.Sprintf("Taglist must be a string, not %T ('%v')", args[0], args[0]))
		}

		tags := strings.Split(taglist, ",")

		for _, tag := range tags {
			re := regexp.MustCompile(fmt.Sprintf("</?%s/?>", tag))
			str = re.ReplaceAllString(str, "")
		}
	} else {
		re := regexp.MustCompile("<[^>]*?>")
		str = re.ReplaceAllString(str, "")
	}

	return strings.TrimSpace(str), nil
}
开发者ID:marcw,项目名称:pongo,代码行数:29,代码来源:filters.go

示例3: removeNonWords

func (this *OCRResult) removeNonWords(blob string) string {
	speller, err := aspell.NewSpeller(map[string]string{
		"lang": "en_US",
	})
	if err != nil {
		fmt.Printf("Error: %s", err.Error())
		return ""
	}
	defer speller.Delete()

	singleCharWords := regexp.MustCompile("(a|i)")
	numberRegex := regexp.MustCompile("\\d{3,}")
	wordRegexp := regexp.MustCompile("\\b(\\w+)\\b")
	words := wordRegexp.FindAllString(blob, -1)

	str := ""

	for _, word := range words {
		if numberRegex.MatchString(word) {
			str += " " + word
		} else if len(word) == 1 {
			if singleCharWords.MatchString(word) {
				str += " " + word
			}
		} else if speller.Check(word) {
			str += " " + word
		}
	}

	return strings.TrimSpace(str)
}
开发者ID:rizzles,项目名称:convert,代码行数:31,代码来源:ocrcommands.go

示例4: singleCalculation

func (calc *Calculator) singleCalculation(calculation string, scope map[string]string) *big.Int {
	regex := regexp.MustCompile(`[\*\+\-\%\/\$\&]`)

	foundOperators := regex.FindAllString(calculation, -1)
	if len(foundOperators) > 1 {
		log.Fatal("Too many operators" + calculation)
		return nil
	}
	operator := foundOperators[0]

	parts := regex.Split(calculation, -1)
	if operator == "+" || operator == "-" || operator == "*" || operator == "%" || operator == "/" || operator == "$" {
		return calc.twoValueCalculation(
			calc.resolveToInt(parts[0], scope),
			calc.resolveToInt(parts[1], scope),
			operator,
		)
	} else if operator == "&" {
		regex = regexp.MustCompile(",")
		g := regex.Split(parts[1], -1)
		return calc.threeValueCalculation(
			calc.resolveToInt(parts[0], scope),
			calc.resolveToInt(g[0], scope),
			calc.resolveToInt(g[1], scope),
			operator,
		)
	}

	return nil
}
开发者ID:VJftw,项目名称:homomorphic-encryption,代码行数:30,代码来源:calculator.go

示例5: TestCornerCases

func TestCornerCases(t *testing.T) {
	testRule1 := Rule{regexp.MustCompile(`(?P<first>\w+)(?:/(?P<second>\w+))?`), V{Corpus: "${first}", Path: "${second}"}.pb()}
	testRule2 := Rule{regexp.MustCompile(`x/(?P<sig>\w+)/y/(?P<tail>.+)$`), V{Path: "${tail}", Sig: "|${sig}|"}.pb()}
	tests := []struct {
		rule  Rule
		input string
		want  *spb.VName
	}{
		// Optional portions of the pattern should be handled correctly.
		{testRule1, "alpha/bravo", V{Corpus: "alpha", Path: "bravo"}.pb()},
		{testRule1, "alpha", V{Corpus: "alpha"}.pb()},

		// Substitution of signature fields should work.
		{testRule2, "x/kanga/y/roo.txt", V{Path: "roo.txt", Sig: "|kanga|"}.pb()},
	}
	for _, test := range tests {
		got, ok := test.rule.Apply(test.input)
		if !ok {
			t.Errorf("Apply %v failed", test.rule)
		} else if !proto.Equal(got, test.want) {
			t.Errorf("Apply %v: got {%+v}, want {%+v}", test.rule, got, test.want)
		} else {
			t.Logf("Apply %v properly returned {%+v}", test.rule, got)
		}
	}
}
开发者ID:herberteuler,项目名称:kythe,代码行数:26,代码来源:rewrite_test.go

示例6: TestReadTriggerParams

func TestReadTriggerParams(t *testing.T) {
	t.Parallel()

	h := newHarness(t)
	defer h.Stop()

	h.env.In = ioutil.NopCloser(strings.NewReader("\n"))
	_, err := readTriggerName(h.env)
	ensure.Err(t, err, regexp.MustCompile("Class name cannot be empty"))

	h.env.In = ioutil.NopCloser(strings.NewReader("foo\n"))
	_, err = readTriggerName(h.env)
	ensure.Err(t, err, regexp.MustCompile("Trigger name cannot be empty"))

	h.env.In = ioutil.NopCloser(strings.NewReader("foo\nbeforeSave"))
	hook, err := readTriggerName(h.env)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, *hook, triggerHook{ClassName: "foo", TriggerName: "beforeSave"})

	h.env.In = ioutil.NopCloser(strings.NewReader("foo\nbeforeSave\napi.example.com/foo/beforeSave\n"))
	hook, err = readTriggerParams(h.env)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, *hook, triggerHook{
		ClassName:   "foo",
		TriggerName: "beforeSave",
		URL:         "https://api.example.com/foo/beforeSave",
	})
}
开发者ID:huamichaelchen,项目名称:parse-cli,代码行数:28,代码来源:triggers_cmd_test.go

示例7: createExceptionNoun

func createExceptionNoun() {
	name := "verb"
	buf := bytes.NewBuffer(nil)
	f, _ := os.Open("/home/serega/Copy/database/dict/" + name + ".exc") // Error handling elided for brevity.
	io.Copy(buf, f)                                                     // Error handling elided for brevity.
	f.Close()
	sentense := (buf.String())
	buf.Reset()
	rubbx = frub.NewRubAr()
	sentense = strings.ToLower(sentense)
	lin := regexp.MustCompile(`\n`).Split(sentense, -1)
	//word := make(ByLength, 2000)
	//wordArray := make([]string, 2000)
	findIsh := make(map[string]string)
	//findForm := make(map[string]map[string]string)
	//fmt.Println(sentense)

	for _, s := range lin {
		words := regexp.MustCompile(` `).Split(s, -1)
		if len(words) == 2 {
			findIsh[words[0]] = words[1]
		}
	}
	fmt.Println(len(findIsh))
	frub.CreateByZn(findIsh, "file/englishLemm/find"+name+".gob")
	wodfFile, _ := os.Create("file/englishLemm/find" + name)
	frub.Encode(findIsh, wodfFile)
	//frub.CreateByZn(findForm, "file/englishLemm/form" + name + ".gob")
	//wodfFile, _ = os.Create("file/englishLemm/form" + name)
	//frub.Encode(findForm, wodfFile)
}
开发者ID:sereg,项目名称:morf,代码行数:31,代码来源:createEnlish.go

示例8: TestLowerPercentile

func TestLowerPercentile(t *testing.T) {
	// Some data with expected mean of 20
	d := []byte("time:0|ms\ntime:1|ms\ntime:2|ms\ntime:3|ms")
	packets := udp.ParseMessage(d, prefix_internal, output, udp.ParseLine)

	pct, _ := timers.NewPercentiles("-75")
	ti := timers.New("", *pct)

	for _, p := range packets {
		ti.Add(p)
	}

	var buff bytes.Buffer
	var num int64
	num += ti.Process(&buff, time.Now().Unix(), 10)

	assert.Equal(t, num, int64(1))
	dataForGraphite := buff.String()

	meanRegexp := regexp.MustCompile(`time\.upper_75 1\.`)
	matched := meanRegexp.MatchString(dataForGraphite)
	assert.Equal(t, matched, false)

	meanRegexp = regexp.MustCompile(`time\.lower_75 1\.`)
	matched = meanRegexp.MatchString(dataForGraphite)
	assert.Equal(t, matched, true)
}
开发者ID:deepglint,项目名称:statsdaemon,代码行数:27,代码来源:statsdaemon_test.go

示例9: handleMessage

func handleMessage(conn *net.UDPConn, remaddr net.Addr, buf *bytes.Buffer) {
	var packet Packet
	var value string
	var sanitizeRegexp = regexp.MustCompile("[^a-zA-Z0-9\\-_\\.:\\|@]")
	var packetRegexp = regexp.MustCompile("([a-zA-Z0-9_]+):(\\-?[0-9\\.]+)\\|(c|ms)(\\|@([0-9\\.]+))?")
	s := sanitizeRegexp.ReplaceAllString(buf.String(), "")
	for _, item := range packetRegexp.FindAllStringSubmatch(s, -1) {
		value = item[2]
		if item[3] == "ms" {
			_, err := strconv.ParseFloat(item[2], 32)
			if err != nil {
				value = "0"
			}
		}

		sampleRate, err := strconv.ParseFloat(item[5], 32)
		if err != nil {
			sampleRate = 1
		}

		packet.Bucket = item[1]
		packet.Value = value
		packet.Modifier = item[3]
		packet.Sampling = float32(sampleRate)

		if *debug {
			log.Println("Packet: bucket = %s, value = %s, modifier = %s, sampling = %f\n", packet.Bucket, packet.Value, packet.Modifier, packet.Sampling)
		}

		In <- packet
	}
}
开发者ID:andreastt,项目名称:statsd-go,代码行数:32,代码来源:main.go

示例10: buildPatterns

func (rte *route) buildPatterns(prefix string) {
	// Don't bother generating fancy regexps if we're looking at '/'
	if rte.segment == "" {
		rte.indexPattern = regexp.MustCompile(`^$`)
	} else {
		basePattern := prefix + rte.segment
		rte.indexPattern = regexp.MustCompile("^" + basePattern + "$")
		if rte.controller != nil {
			patternWithId := fmt.Sprintf(`^%s(?:/(?P<%s_id>%s))?$`, basePattern, strings.Replace(NameFromController(rte.controller), "-", "_", -1), rte.controller.IdPattern())
			rte.objectPattern = regexp.MustCompile(patternWithId)
			actions := rte.controller.extraActionNames()
			if len(actions) > 0 {
				actionPatternString := fmt.Sprintf(`^%s/(?:%s)$`, basePattern, strings.Join(actions, "|"))
				rte.actionPattern = regexp.MustCompile(actionPatternString)
			}
		}
	}
	// Calls to Prefixed generate routes without controllers, and the value of prefix is already all set for those
	if rte.controller != nil {
		prefix += fmt.Sprintf(`%s/(?P<%s_id>%s)/`, rte.segment, NameFromController(rte.controller), rte.controller.IdPattern())
	} else {
		prefix += "/"
	}
	for _, r := range rte.subroutes {
		r.buildPatterns(prefix)
	}
}
开发者ID:ustbgaofan,项目名称:gadget,代码行数:27,代码来源:route.go

示例11: TestNewRSRField1

func TestNewRSRField1(t *testing.T) {
	// Normal case
	expRSRField1 := &RSRField{Id: "sip_redirected_to",
		RSRules: []*ReSearchReplace{&ReSearchReplace{SearchRegexp: regexp.MustCompile(`sip:\+49(\d+)@`), ReplaceTemplate: "0$1"}}}
	if rsrField, err := NewRSRField(`~sip_redirected_to:s/sip:\+49(\d+)@/0$1/`); err != nil {
		t.Error("Unexpected error: ", err.Error())
	} else if !reflect.DeepEqual(expRSRField1, rsrField) {
		t.Errorf("Expecting: %v, received: %v", expRSRField1, rsrField)
	}
	// With filter
	filter, _ := NewRSRFilter("086517174963")
	expRSRField2 := &RSRField{Id: "sip_redirected_to", filters: []*RSRFilter{filter},
		RSRules: []*ReSearchReplace{&ReSearchReplace{SearchRegexp: regexp.MustCompile(`sip:\+49(\d+)@`), ReplaceTemplate: "0$1"}}}
	if rsrField, err := NewRSRField(`~sip_redirected_to:s/sip:\+49(\d+)@/0$1/(086517174963)`); err != nil {
		t.Error("Unexpected error: ", err.Error())
	} else if !reflect.DeepEqual(expRSRField2, rsrField) {
		t.Errorf("Expecting: %v, received: %v", expRSRField2, rsrField)
	}
	// Separator escaped
	if rsrField, err := NewRSRField(`~sip_redirected_to:s\/sip:\+49(\d+)@/0$1/`); err == nil {
		t.Errorf("Parse error, field rule does not contain correct number of separators, received: %v", rsrField)
	}
	// One extra separator but escaped
	expRSRField3 := &RSRField{Id: "sip_redirected_to",
		RSRules: []*ReSearchReplace{&ReSearchReplace{SearchRegexp: regexp.MustCompile(`sip:\+49(\d+)\/@`), ReplaceTemplate: "0$1"}}}
	if rsrField, err := NewRSRField(`~sip_redirected_to:s/sip:\+49(\d+)\/@/0$1/`); err != nil {
		t.Error("Unexpected error: ", err.Error())
	} else if !reflect.DeepEqual(expRSRField3, rsrField) {
		t.Errorf("Expecting: %v, received: %v", expRSRField3, rsrField)
	}
}
开发者ID:razvancrainea,项目名称:cgrates,代码行数:31,代码来源:rsrfield_test.go

示例12: FindTaskId

func FindTaskId(index string, autoFirst bool) string {
	if index == "" {
		if autoFirst == false {
			log.Fatal("fatal: Task index is required.")
		} else {
			index = "0"
		}
	}

	var id string
	txt, err := ioutil.ReadFile(utils.CacheFile())

	if err != nil { // cache file not exist
		ind, parseErr := strconv.Atoi(index)
		utils.Check(parseErr)
		task := Tasks(url.Values{}, false)[ind]
		id = strconv.Itoa(task.Id)
	} else {
		lines := regexp.MustCompile("\n").Split(string(txt), -1)
		for i, line := range lines {
			if index == strconv.Itoa(i) {
				line = regexp.MustCompile("^[0-9]*:").ReplaceAllString(line, "") // remove index
				id = regexp.MustCompile("^[0-9]*").FindString(line)
			}
		}
	}
	return id
}
开发者ID:clemens-tolboom,项目名称:asana,代码行数:28,代码来源:task.go

示例13: Run

func (b *BotClient) Run() {
	// Regexes
	// Add the matcher here
	privmsgRegexp := regexp.MustCompile("^:(.+?)!(.+?)@(.+?)\\sPRIVMSG\\s(.+?)\\s:(.+)$")
	modeRegexp := regexp.MustCompile("^:(.+?)!(.+?)@(.+?)\\sMODE\\s(.+?)\\s(.+)$")

	for {
		str := <-b.ReadChan
		if str[0:6] == "PING :" {
			if b.debug {
				fmt.Printf("\033[34mSERVER PING\033[0m\n")
			}
			b.WriteChan <- "PONG :" + str[7:]
		}

		data := privmsgRegexp.FindAllStringSubmatch(str, 1)
		if data != nil {
			b.processPrivMsg(data)
		}

		data = modeRegexp.FindAllStringSubmatch(str, 1)
		if data != nil {
			b.processModeMsg(data)
		}

		// and add the handler function here
	}
}
开发者ID:JingxuanWang,项目名称:Playground,代码行数:28,代码来源:irc_bot.go

示例14: Watch

func (this *gowatch) Watch() (err error) {
	if this.w, err = fsnotify.NewWatcher(); err != nil {
		return
	}
	for _, path := range this.Paths {
		if err = this.watchDirAndChildren(os.ExpandEnv(path)); err != nil {
			log.Fatal(err)
		}
	}
	this.modtime = make(map[string]time.Time)
	this.sig = make(chan string)
	for _, patten := range this.Exclude {
		this.reExclude = append(this.reExclude, regexp.MustCompile(patten))
	}
	for _, patten := range this.Include {
		this.reInclude = append(this.reInclude, regexp.MustCompile(patten))
	}

	this.sigOS = make(chan os.Signal, 1)
	signal.Notify(this.sigOS, syscall.SIGINT)

	go this.drainExec()
	this.drainEvent()
	return
}
开发者ID:nXqd,项目名称:fswatch,代码行数:25,代码来源:fswatch.go

示例15: TestAccAWSEcsServiceWithRenamedCluster

// Regression for https://github.com/hashicorp/terraform/issues/2427
func TestAccAWSEcsServiceWithRenamedCluster(t *testing.T) {
	originalRegexp := regexp.MustCompile(
		"^arn:aws:ecs:[^:]+:[0-9]+:cluster/terraformecstest3$")
	modifiedRegexp := regexp.MustCompile(
		"^arn:aws:ecs:[^:]+:[0-9]+:cluster/terraformecstest3modified$")

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAWSEcsServiceDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccAWSEcsServiceWithRenamedCluster,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSEcsServiceExists("aws_ecs_service.ghost"),
					resource.TestMatchResourceAttr(
						"aws_ecs_service.ghost", "cluster", originalRegexp),
				),
			},

			resource.TestStep{
				Config: testAccAWSEcsServiceWithRenamedClusterModified,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSEcsServiceExists("aws_ecs_service.ghost"),
					resource.TestMatchResourceAttr(
						"aws_ecs_service.ghost", "cluster", modifiedRegexp),
				),
			},
		},
	})
}
开发者ID:devendraPSL,项目名称:terraform-api,代码行数:32,代码来源:resource_aws_ecs_service_test.go


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