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


Golang Regexp.String方法代码示例

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


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

示例1: AddResponse

func (m *Module) AddResponse(reg *regexp.Regexp, f func(*Response), permission permissions.Permission) error {
	name := reg.String()
	wrap := func(message *irc.Message) {
		switch message.Command {
		case "PRIVMSG", "NOTICE":
			nick := message.Server.CurrentNick()
			text := strings.Join(message.Arguments[1:], " ")
			if message.Arguments[0] == nick { //direct privmsg
				if reg.MatchString(strings.Trim(text, " ")) {
					f(&Response{message, text, reg.FindStringSubmatch(text)})
				}
			} else { //asked from channel
				current, err := regexp.Compile("^" + nick + "[ ,;:]")
				if err != nil {
					log.Error("Failed to compile nick regexp: ", err)
				} else if current.MatchString(text) {
					nl := len(nick) + 1
					if len(text) > nl {
						just_text := strings.Trim(text[nl:], " ")
						if reg.MatchString(just_text) {
							f(&Response{message, text, reg.FindStringSubmatch(just_text)})
						}
					}
				}
			}
		}
	}

	if _, ok := m.handlers[name]; ok {
		return errors.New("Response with same regexp already exist's!")
	}

	m.handlers[name] = m.connection.AddHandler(wrap, permission)
	return nil
}
开发者ID:natrim,项目名称:grainbot,代码行数:35,代码来源:responses.go

示例2: RegexpFilter

func RegexpFilter(filterReg *regexp.Regexp, data []byte) (outdata []byte) {
	if nil == filterReg {
		return data
	}

	matches := filterReg.FindAllSubmatch(data, -1)
	if nil == matches {
		log.Printf("[ERROR] failed to match filter regex, pattern %s did not match", filterReg.String())
		if *gDebug {
			log.Println("======= debug: target data =======")
			log.Println(string(data))
			log.Println("==============")
		}
		return nil
	}

	for _, match := range matches {
		for patInd, patName := range filterReg.SubexpNames() {
			switch patName {
			case PATTERN_FILTER:
				outdata = append(outdata, match[patInd]...)
			}
		}
	}

	if *gDebug {
		log.Println("======= debug: filter regex ========")
		log.Println(filterReg.String())
		log.Println("======= debug: filtered data =======")
		log.Println(string(outdata))
		log.Println("==============")
	}
	return
}
开发者ID:wizos,项目名称:gofeed,代码行数:34,代码来源:filter.go

示例3: GetParamRegexp

func GetParamRegexp(r *http.Request, param string, re *regexp.Regexp) (string, error) {
	s := GetParam(r, param)
	if !re.MatchString(s) {
		return "", fmt.Errorf(param, "Did not match regular expression %v", re.String())
	}
	return s, nil
}
开发者ID:readevalprint,项目名称:eris-db,代码行数:7,代码来源:http_params.go

示例4: verifyStructStringsAgainstWhitelist

// FIXME: too much magic, just do explicit validation of the few
//        fields we have
// verifyStructStringsAgainstWhitelist takes a struct and ensures that
// the given whitelist regexp matches all string fields of the struct
func verifyStructStringsAgainstWhitelist(s interface{}, whitelist *regexp.Regexp) error {
	// check all members of the services struct against our whitelist
	t := reflect.TypeOf(s)
	v := reflect.ValueOf(s)
	for i := 0; i < t.NumField(); i++ {

		// PkgPath means its a unexported field and we can ignore it
		if t.Field(i).PkgPath != "" {
			continue
		}
		if v.Field(i).Kind() == reflect.Ptr {
			vi := v.Field(i).Elem()
			if vi.Kind() == reflect.Struct {
				return verifyStructStringsAgainstWhitelist(vi.Interface(), whitelist)
			}
		}
		if v.Field(i).Kind() == reflect.Struct {
			vi := v.Field(i).Interface()
			return verifyStructStringsAgainstWhitelist(vi, whitelist)
		}
		if v.Field(i).Kind() == reflect.String {
			key := t.Field(i).Name
			value := v.Field(i).String()
			if !whitelist.MatchString(value) {
				return &ErrStructIllegalContent{
					Field:     key,
					Content:   value,
					Whitelist: whitelist.String(),
				}
			}
		}
	}

	return nil
}
开发者ID:alecu,项目名称:snappy,代码行数:39,代码来源:click.go

示例5: TestMatchResourceAttr

func TestMatchResourceAttr(name, key string, r *regexp.Regexp) TestCheckFunc {
	return func(s *terraform.State) error {
		ms := s.RootModule()
		rs, ok := ms.Resources[name]
		if !ok {
			return fmt.Errorf("Not found: %s", name)
		}

		is := rs.Primary
		if is == nil {
			return fmt.Errorf("No primary instance: %s", name)
		}

		if !r.MatchString(is.Attributes[key]) {
			return fmt.Errorf(
				"%s: Attribute '%s' didn't match %q, got %#v",
				name,
				key,
				r.String(),
				is.Attributes[key])
		}

		return nil
	}
}
开发者ID:monkeylittleinc,项目名称:terraform,代码行数:25,代码来源:testing.go

示例6: NewRegexMatcher

// NewRegexMatcher returns a new matcher that compares values against
// a regular expression. The matcher is already initialized.
//
// TODO(fabxc): refactor usage.
func NewRegexMatcher(name model.LabelName, re *regexp.Regexp) *Matcher {
	return &Matcher{
		Name:    string(name),
		Value:   re.String(),
		IsRegex: true,
		regex:   re,
	}
}
开发者ID:farcaller,项目名称:alertmanager,代码行数:12,代码来源:match.go

示例7: safelyCall

func (route *Route) safelyCall(args []reflect.Value, routePath *regexp.Regexp) (result []reflect.Value, err interface{}) {
	defer func() {
		if err = recover(); err != nil {
			log.Println("Handler for route", routePath.String(), "paniced with", err)
		}
	}()
	return route.handler.Call(args), err
}
开发者ID:dbrain,项目名称:soggy,代码行数:8,代码来源:router.go

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

示例9: Regexp

func Regexp(p *regexp.Regexp) Validator {
	return NewFuncValidator(func(v *Value, r Requester) error {
		if !p.MatchString(v.RawString()) {
			return ErrRegexp.Err([]interface{}{v.Name(), p.String()}...)
		}
		return nil
	}, MsgRegexp.Msg(p.String()))
}
开发者ID:wlMalk,项目名称:gapi,代码行数:8,代码来源:validators.go

示例10: sketchOnRegex

/*
I'm sorry, dear reader. I really am.

The problem here is to take an arbitrary regular expression and:
1. return a regular expression that is just like it, but left-anchored,
   preferring to return the original if possible.
2. determine a string literal prefix that all matches of this regular expression
   have, much like regexp.Regexp.Prefix(). Unfortunately, Prefix() does not work
   in the presence of anchors, so we need to write it ourselves.

What this actually means is that we need to sketch on the internals of the
standard regexp library to forcefully extract the information we want.

Unfortunately, regexp.Regexp hides a lot of its state, so our abstraction is
going to be pretty leaky. The biggest leak is that we blindly assume that all
regular expressions are perl-style, not POSIX. This is probably Mostly True, and
I think most users of the library probably won't be able to notice.
*/
func sketchOnRegex(re *regexp.Regexp) (*regexp.Regexp, string) {
	rawRe := re.String()
	sRe, err := syntax.Parse(rawRe, syntax.Perl)
	if err != nil {
		log.Printf("WARN(web): unable to parse regexp %v as perl. "+
			"This route might behave unexpectedly.", re)
		return re, ""
	}
	sRe = sRe.Simplify()
	p, err := syntax.Compile(sRe)
	if err != nil {
		log.Printf("WARN(web): unable to compile regexp %v. This "+
			"route might behave unexpectedly.", re)
		return re, ""
	}
	if p.StartCond()&syntax.EmptyBeginText == 0 {
		// I hope doing this is always legal...
		newRe, err := regexp.Compile(`\A` + rawRe)
		if err != nil {
			log.Printf("WARN(web): unable to create a left-"+
				"anchored regexp from %v. This route might "+
				"behave unexpectedly", re)
			return re, ""
		}
		re = newRe
	}

	// Run the regular expression more or less by hand :(
	pc := uint32(p.Start)
	atStart := true
	i := &p.Inst[pc]
	var buf bytes.Buffer
Sadness:
	for {
		switch i.Op {
		case syntax.InstEmptyWidth:
			if !atStart {
				break Sadness
			}
		case syntax.InstCapture, syntax.InstNop:
			// nop!
		case syntax.InstRune, syntax.InstRune1, syntax.InstRuneAny,
			syntax.InstRuneAnyNotNL:

			atStart = false
			if len(i.Rune) != 1 ||
				syntax.Flags(i.Arg)&syntax.FoldCase != 0 {
				break Sadness
			}
			buf.WriteRune(i.Rune[0])
		default:
			break Sadness
		}
		pc = i.Out
		i = &p.Inst[pc]
	}
	return re, buf.String()
}
开发者ID:RuiAAPeres,项目名称:OctifyPush,代码行数:76,代码来源:pattern.go

示例11: HasResultForFileAndPattern

func (rs *SearchResults) HasResultForFileAndPattern(si *SearchItem,
	pattern *regexp.Regexp) bool {
	for _, r := range rs.SearchResults {
		if pattern.String() == r.Pattern.String() && si.String() == r.File.String() {
			return true
		}
	}
	return false
}
开发者ID:clarkcb,项目名称:xsearch,代码行数:9,代码来源:searchresults.go

示例12: newRegexpCache

func newRegexpCache(r *regexp.Regexp) *regexpCache {
	s := r.String()
	re, _ := syntax.Parse(s, syntax.Perl)
	return &regexpCache{
		re:    re,
		min:   minCap(re),
		max:   re.MaxCap(),
		cache: make(map[string]*regexp.Regexp),
	}
}
开发者ID:rainycape,项目名称:gondola,代码行数:10,代码来源:regexp.go

示例13: literalRegexp

func literalRegexp(r *regexp.Regexp) string {
	re, _ := syntax.Parse(r.String(), syntax.Perl)
	if re.MaxCap() == 0 && re.Op == syntax.OpConcat && len(re.Sub) == 3 &&
		re.Sub[0].Op == syntax.OpBeginText &&
		re.Sub[1].Op == syntax.OpLiteral &&
		re.Sub[2].Op == syntax.OpEndText {

		return string(re.Sub[1].Rune)
	}
	return ""
}
开发者ID:rainycape,项目名称:gondola,代码行数:11,代码来源:regexp.go

示例14: NewRegexMatcher

// NewRegexMatcher returns a new matcher that treats value as a regular
// expression which is used for matching.
func NewRegexMatcher(name model.LabelName, re *regexp.Regexp) *Matcher {
	value := strings.TrimSuffix(strings.TrimPrefix(re.String(), "^(?:"), ")$")
	if len(re.String())-len(value) != 6 {
		// Any non-anchored regexp is a bug.
		panic(fmt.Errorf("regexp %q not properly anchored", re))
	}
	return &Matcher{
		Name:    name,
		Value:   value,
		isRegex: true,
		regex:   re,
	}
}
开发者ID:craig-mulligan,项目名称:alertmanager,代码行数:15,代码来源:match.go

示例15: Regexp

func Regexp(re *regexp.Regexp) func(v reflect.Value) error {
	return func(v reflect.Value) error {
		if v.Kind() != reflect.String {
			return fmt.Errorf("must be a string")
		}

		if !re.MatchString(v.String()) {
			return fmt.Errorf("must be %s", re.String())
		}

		return nil
	}
}
开发者ID:choirudin2210,项目名称:platform-layer,代码行数:13,代码来源:rules.go


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