本文整理汇总了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)
}
示例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
}
示例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)
}
示例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
}
示例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)
}
}
}
示例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",
})
}
示例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)
}
示例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)
}
示例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
}
}
示例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)
}
}
示例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)
}
}
示例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
}
示例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
}
}
示例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
}
示例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),
),
},
},
})
}