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


Golang regexp.QuoteMeta函数代码示例

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


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

示例1: compile

func (r *Route) compile() {
	segments := strings.Split(r.Path, "/")
	compiledSegments := make([]string, len(segments))

	for i, segment := range segments {
		switch {
		case namedSegmentRegexp.MatchString(segment):
			segmentName := regexp.QuoteMeta(segment[1:len(segment)])
			constraint := defaultConstraint

			if _, hit := r.Constraints[segmentName]; hit {
				constraint = r.Constraints[segmentName]
			}

			segment = "(?P<" + segmentName + ">" + constraint + ")"
		default:
			segment = regexp.QuoteMeta(segment)
		}
		compiledSegments[i] = segment
	}

	regexpSource := "^" + strings.Join(compiledSegments, "/") + formantConstraint

	if !r.mounted {
		regexpSource += "$"
	}

	r.regexp = regexp.MustCompile(regexpSource)
}
开发者ID:rosylilly,项目名称:ape,代码行数:29,代码来源:route.go

示例2: TestExecArgsMismatch

func TestExecArgsMismatch(t *testing.T) {
	c := &conn{
		expectations: []expectation{
			&expectedExec{
				queryBasedExpectation: queryBasedExpectation{
					commonExpectation: commonExpectation{
						err: errors.New("WillReturnError"),
					},
					sqlRegex: regexp.MustCompile(regexp.QuoteMeta("query")),
					args:     []driver.Value{456},
				},
			},
		},
	}
	res, err := c.Exec("query", []driver.Value{123})
	if res != nil {
		t.Error("Result should be nil")
	}
	if err == nil {
		t.Error("error should not be nil")
	}
	pattern := regexp.MustCompile(regexp.QuoteMeta("does not match expected"))
	if !pattern.MatchString(err.Error()) {
		t.Errorf("error should match expected error message (actual: %s)", err.Error())
	}
}
开发者ID:brunoqc,项目名称:go-sqlmock,代码行数:26,代码来源:connection_test.go

示例3: TestRaceMissing

// check that missing -race support generates error message.
func TestRaceMissing(t *testing.T) {
	if canRace {
		t.Skip("skipping because race detector is available")
	}

	gb := T{T: t}
	defer gb.cleanup()

	gb.tempDir("src/race")
	gb.tempFile("src/race/map_test.go", `package race
import "testing"

func TestRaceMapRW(t *testing.T) {
        m := make(map[int]int)
        ch := make(chan bool, 1)
        go func() {
                _ = m[1]
                ch <- true
        }()
        m[1] = 1
        <-ch
}
`)
	gb.cd(gb.tempdir)
	tmpdir := gb.tempDir("tmp")
	gb.setenv("TMP", tmpdir)
	gb.runFail("test", "-race")
	raceError1 := fmt.Sprintf("FATAL: go installation at %s is missing race support", runtime.GOROOT())
	raceError2 := fmt.Sprintf("FATAL: race detector not supported on %s/%s", runtime.GOOS, runtime.GOARCH)
	gb.grepStderr(regexp.QuoteMeta(raceError1)+"|"+regexp.QuoteMeta(raceError2), "expected missing race support message")
	gb.mustBeEmpty(tmpdir)
}
开发者ID:hyper-carrot,项目名称:gb,代码行数:33,代码来源:gb_test.go

示例4: compilePattern

// compilePattern compiles the pattern to a regexp and array of parameter names.
func compilePattern(pattern string, addSlash bool, sep string) (*regexp.Regexp, []string) {
	var buf bytes.Buffer
	names := make([]string, 8)
	i := 0
	buf.WriteString("^")
	for {
		a := parameterRegexp.FindStringSubmatchIndex(pattern)
		if len(a) == 0 {
			buf.WriteString(regexp.QuoteMeta(pattern))
			break
		} else {
			buf.WriteString(regexp.QuoteMeta(pattern[0:a[0]]))
			name := pattern[a[2]:a[3]]
			if name != "" {
				names[i] = pattern[a[2]:a[3]]
				i += 1
				buf.WriteString("(")
			}
			if a[4] >= 0 {
				buf.WriteString(pattern[a[4]+1 : a[5]])
			} else {
				buf.WriteString("[^" + sep + "]+")
			}
			if name != "" {
				buf.WriteString(")")
			}
			pattern = pattern[a[1]:]
		}
	}
	if addSlash {
		buf.WriteString("?")
	}
	buf.WriteString("$")
	return regexp.MustCompile(buf.String()), names[0:i]
}
开发者ID:chillicoder,项目名称:twister,代码行数:36,代码来源:router.go

示例5: build

func build(path string, data interface{}) (*route, error) {
	var buf bytes.Buffer
	dups := make(map[string]bool)
	for _, paths := range pathRegexp.FindAllStringSubmatch(path, -1) {
		name := paths[1] + paths[2]
		if name == "" {
			// don't have path parameters.
			buf.WriteString(regexp.QuoteMeta(paths[0]))
			continue
		}
		var pathReStr string
		if pathReStr = paramRegexpStr[name[0]]; pathReStr == "" {
			pathReStr = defaultParamRegexpStr
		} else {
			if dups[name] {
				return nil, fmt.Errorf("path parameter `%v` is duplicated in the key '%v'", name, path)
			}
			dups[name] = true
			name = name[1:] // truncate a meta character.
		}
		buf.WriteString(fmt.Sprintf(`/(?P<%s>%s)`, regexp.QuoteMeta(name), pathReStr))
	}
	reg, err := regexp.Compile(fmt.Sprintf(`^%s$`, buf.String()))
	if err != nil {
		return nil, err
	}
	return &route{regexp: reg, data: data}, nil
}
开发者ID:naoina,项目名称:kocha-urlrouter,代码行数:28,代码来源:regexp.go

示例6: compileRegexp

// compileRegexp compiles our route format to a true regexp
// Both name and regexp are required - routes should be well structured and restrictive by default
// Convert the pattern from the form  /pages/{id:[0-9]*}/edit?param=test
// to one suitable for regexp -  /pages/([0-9]*)/edit\?param=test
// We want to match things like this:
// /pages/{id:[0-9]*}/edit
// /pages/{id:[0-9]*}/edit?param=test
func (r *Route) compileRegexp() (err error) {
	// Check if it is well-formed.
	idxs, errBraces := r.findBraces(r.Pattern)
	if errBraces != nil {
		return errBraces
	}

	pattern := bytes.NewBufferString("^")
	end := 0

	// Walk through indexes two at a time
	for i := 0; i < len(idxs); i += 2 {
		// Set all values we are interested in.
		raw := r.Pattern[end:idxs[i]]
		end = idxs[i+1]
		parts := strings.SplitN(r.Pattern[idxs[i]+1:end-1], ":", 2)
		if len(parts) != 2 {
			return fmt.Errorf("Missing name or pattern in %s", raw)
		}

		// Add the Argument name
		r.ParamNames = append(r.ParamNames, parts[0])

		// Add the real regexp
		fmt.Fprintf(pattern, "%s(%s)", regexp.QuoteMeta(raw), parts[1])

	}
	// Add the remaining pattern
	pattern.WriteString(regexp.QuoteMeta(r.Pattern[end:]))
	r.Regexp, err = regexp.Compile(pattern.String())

	return err
}
开发者ID:fragmenta,项目名称:router,代码行数:40,代码来源:route.go

示例7: CreateMux

func CreateMux(text string) *Mux {
	// parse the text into a regexp
	re := regexp.MustCompile(`:[A-Z]\w*`)
	matches := re.FindAllStringIndex(text, -1)

	restring := "^"
	pos := 0
	variables := []string{}
	for _, match := range matches {
		start := match[0]
		end := match[1]
		// Everything since the last match
		// Should check for evil characters
		restring += regexp.QuoteMeta(text[pos:start])
		pos = end
		// Turn this into an RE
		// Should the RE be more restrictive?
		restring += `([^/]*)`
		variables = append(variables, text[start+1:end])
	}
	restring += regexp.QuoteMeta(text[pos:])
	restring += "$"
	muxre := regexp.MustCompile(restring)

	return &Mux{text: text, muxRegexp: muxre, variables: variables}
}
开发者ID:mrlauer,项目名称:pdfmaker,代码行数:26,代码来源:mux.go

示例8: translateBraketExpression

// Braket expression wildcard. Except for the beginning
// exclamation mark, the whole braket expression can be used
// directly as regex but we have to find where the expression
// ends.
// - "[][!]" matchs ']', '[' and '!'.
// - "[]-]" matchs ']' and '-'.
// - "[!]a-]" matchs any character except ']', 'a' and '-'.
func translateBraketExpression(i *int, glob string) string {
	regex := string(glob[*i])
	*i++
	j := *i

	// Pass brack expression negation.
	if j < len(glob) && glob[j] == '!' {
		j++
	}
	// Pass first closing braket if it is at the beginning of the
	// expression.
	if j < len(glob) && glob[j] == ']' {
		j++
	}
	// Find closing braket. Stop once we reach the end or find it.
	for j < len(glob) && glob[j] != ']' {
		j++
	}

	if j < len(glob) {
		if glob[*i] == '!' {
			regex = regex + "^"
			*i++
		}
		regex = regexp.QuoteMeta(glob[*i:j])
		*i = j
	} else {
		// Failed to find closing braket, treat opening braket as a
		// braket literal instead of as an expression.
		regex = regexp.QuoteMeta(string(glob[*i]))
	}
	return "[" + regex + "]"
}
开发者ID:rliebling,项目名称:gitignorer,代码行数:40,代码来源:gitignore.go

示例9: TestHelp

// TestHelp runs the command with --help as argument and verifies the
// output.
func (s *BaseSpaceSuite) TestHelp(c *gc.C) {
	stderr, stdout, err := s.RunSuperCommand(c, "--help")
	c.Assert(err, jc.ErrorIsNil)
	c.Check(stdout, gc.Equals, "")
	c.Check(stderr, gc.Not(gc.Equals), "")

	// If s.command is set, use it instead of s.superCmd.
	cmdInfo := s.superCmd.Info()
	var expected string
	if s.command != nil {
		// Subcommands embed ModelCommandBase
		cmdInfo = s.command.Info()
		expected = "(?sm).*^Usage: juju space " +
			regexp.QuoteMeta(cmdInfo.Name) +
			`( \[options\])? ` + regexp.QuoteMeta(cmdInfo.Args) + ".+"
	} else {
		expected = "(?sm).*^Usage: juju space" +
			`( \[options\])? ` + regexp.QuoteMeta(cmdInfo.Args) + ".+"
	}
	c.Check(cmdInfo, gc.NotNil)
	c.Check(stderr, gc.Matches, expected)

	expected = "(?sm).*^Summary:\n" + regexp.QuoteMeta(cmdInfo.Purpose) + "$.*"
	c.Check(stderr, gc.Matches, expected)

	expected = "(?sm).*^Details:\n" + regexp.QuoteMeta(cmdInfo.Doc) + "$.*"
	c.Check(stderr, gc.Matches, expected)
}
开发者ID:AlexisBruemmer,项目名称:juju,代码行数:30,代码来源:package_test.go

示例10: TestReadHeaderLogsRequests

func (*suite) TestReadHeaderLogsRequests(c *gc.C) {
	codecLogger := loggo.GetLogger("juju.rpc.jsoncodec")
	defer codecLogger.SetLogLevel(codecLogger.LogLevel())
	codecLogger.SetLogLevel(loggo.TRACE)
	msg := `{"RequestId":1,"Type": "foo","Id": "id","Request":"frob","Params":{"X":"param"}}`
	codec := jsoncodec.New(&testConn{
		readMsgs: []string{msg, msg, msg},
	})
	// Check that logging is off by default
	var h rpc.Header
	err := codec.ReadHeader(&h)
	c.Assert(err, gc.IsNil)
	c.Assert(c.GetTestLog(), gc.Matches, "")

	// Check that we see a log message when we switch logging on.
	codec.SetLogging(true)
	err = codec.ReadHeader(&h)
	c.Assert(err, gc.IsNil)
	c.Assert(c.GetTestLog(), gc.Matches, ".*TRACE juju.rpc.jsoncodec <- "+regexp.QuoteMeta(msg)+`\n`)

	// Check that we can switch it off again
	codec.SetLogging(false)
	err = codec.ReadHeader(&h)
	c.Assert(err, gc.IsNil)
	c.Assert(c.GetTestLog(), gc.Matches, ".*TRACE juju.rpc.jsoncodec <- "+regexp.QuoteMeta(msg)+`\n`)
}
开发者ID:rogpeppe,项目名称:juju,代码行数:26,代码来源:codec_test.go

示例11: TestWriteMessageLogsRequests

func (*suite) TestWriteMessageLogsRequests(c *C) {
	codec := jsoncodec.New(&testConn{})
	h := rpc.Header{
		RequestId: 1,
		Type:      "foo",
		Id:        "id",
		Request:   "frob",
	}

	// Check that logging is off by default
	err := codec.WriteMessage(&h, value{X: "param"})
	c.Assert(err, IsNil)
	c.Assert(c.GetTestLog(), Matches, "")

	// Check that we see a log message when we switch logging on.
	codec.SetLogging(true)
	err = codec.WriteMessage(&h, value{X: "param"})
	c.Assert(err, IsNil)
	msg := `{"RequestId":1,"Type":"foo","Id":"id","Request":"frob","Params":{"X":"param"}}`
	c.Assert(c.GetTestLog(), Matches, `.*DEBUG juju rpc/jsoncodec: -> `+regexp.QuoteMeta(msg)+`\n`)

	// Check that we can switch it off again
	codec.SetLogging(false)
	err = codec.WriteMessage(&h, value{X: "param"})
	c.Assert(err, IsNil)
	c.Assert(c.GetTestLog(), Matches, `.*DEBUG juju rpc/jsoncodec: -> `+regexp.QuoteMeta(msg)+`\n`)
}
开发者ID:johnvilsack,项目名称:golang-stuff,代码行数:27,代码来源:codec_test.go

示例12: checkCanUpgrade

func (st *State) checkCanUpgrade(currentVersion, newVersion string) error {
	matchCurrent := "^" + regexp.QuoteMeta(currentVersion) + "-"
	matchNew := "^" + regexp.QuoteMeta(newVersion) + "-"
	// Get all machines and units with a different or empty version.
	sel := bson.D{{"$or", []bson.D{
		{{"tools", bson.D{{"$exists", false}}}},
		{{"$and", []bson.D{
			{{"tools.version", bson.D{{"$not", bson.RegEx{matchCurrent, ""}}}}},
			{{"tools.version", bson.D{{"$not", bson.RegEx{matchNew, ""}}}}},
		}}},
	}}}
	var agentTags []string
	for _, collection := range []*mgo.Collection{st.machines, st.units} {
		var doc struct {
			Id string `bson:"_id"`
		}
		iter := collection.Find(sel).Select(bson.D{{"_id", 1}}).Iter()
		for iter.Next(&doc) {
			switch collection.Name {
			case "machines":
				agentTags = append(agentTags, names.NewMachineTag(doc.Id).String())
			case "units":
				agentTags = append(agentTags, names.NewUnitTag(doc.Id).String())
			}
		}
		if err := iter.Close(); err != nil {
			return err
		}
	}
	if len(agentTags) > 0 {
		return newVersionInconsistentError(version.MustParse(currentVersion), agentTags)
	}
	return nil
}
开发者ID:klyachin,项目名称:juju,代码行数:34,代码来源:state.go

示例13: importSnippet

func importSnippet(subsitutions []string) (ok bool) {
	for _, sub := range subsitutions {
		if len(sub) < 4 {
			fmt.Fprintf(os.Stderr, "invalid substitution: %q\n", sub)
			return
		}
		delim := sub[1:2]
		// TODO(gaal): paired delimiters, e.g., s{foo}{bar}
		parse := regexp.MustCompile("^s" + delim +
			`((?:\\.|[^` + regexp.QuoteMeta(delim) + `])*)` + delim +
			`((?:\\.|[^` + regexp.QuoteMeta(delim) + `])*)` + delim + "([ig])*$")
		parsedSub := parse.FindStringSubmatch(sub)
		if len(parsedSub) != 4 {
			fmt.Fprint(os.Stderr, "invalid substitution: ", sub)
			return
		}
		global := strings.Contains(parsedSub[3], "g")
		ignoreCase := strings.Contains(parsedSub[3], "i")
		pat := parsedSub[1]
		if ignoreCase {
			pat = "(?i)" + pat
		}
		if search, err := regexp.Compile(pat); err == nil {
			substitutionVals = append(substitutionVals, Substitution{search, parsedSub[2], global})
		} else {
			fmt.Fprint(os.Stderr, "invalid substitution: ", sub)
			return
		}
	}
	return true
}
开发者ID:gaal,项目名称:prolix-go,代码行数:31,代码来源:prolix.go

示例14: TestHelp

// TestHelp runs the command with --help as argument and verifies the
// output.
func (s *BaseSubnetSuite) TestHelp(c *gc.C) {
	stderr, stdout, err := s.RunSuperCommand(c, "--help")
	c.Assert(err, jc.ErrorIsNil)
	c.Check(stdout, gc.Equals, "")
	c.Check(stderr, gc.Not(gc.Equals), "")

	// If s.command is set, use it instead of s.superCmd.
	cmdInfo := s.superCmd.Info()
	var expected string
	if s.command != nil {
		// Subcommands embed ModelCommandBase and have an extra
		// "[options]" prepended before the args.
		cmdInfo = s.command.Info()
		expected = "(?sm).*^usage: juju subnet " +
			regexp.QuoteMeta(cmdInfo.Name) +
			`( \[options\])? ` + regexp.QuoteMeta(cmdInfo.Args) + ".+"
	} else {
		expected = "(?sm).*^usage: juju subnet" +
			`( \[options\])? ` + regexp.QuoteMeta(cmdInfo.Args) + ".+"
	}
	c.Check(cmdInfo, gc.NotNil)
	c.Check(stderr, gc.Matches, expected)

	expected = "(?sm).*^purpose: " + regexp.QuoteMeta(cmdInfo.Purpose) + "$.*"
	c.Check(stderr, gc.Matches, expected)

	expected = "(?sm).*^" + regexp.QuoteMeta(cmdInfo.Doc) + "$.*"
	c.Check(stderr, gc.Matches, expected)
}
开发者ID:exekias,项目名称:juju,代码行数:31,代码来源:package_test.go

示例15: TestExecNoExpectations

func TestExecNoExpectations(t *testing.T) {
	c := &conn{
		expectations: []expectation{
			&expectedExec{
				queryBasedExpectation: queryBasedExpectation{
					commonExpectation: commonExpectation{
						triggered: true,
						err:       errors.New("WillReturnError"),
					},
					sqlRegex: regexp.MustCompile(regexp.QuoteMeta("otherquery")),
					args:     []driver.Value{456},
				},
			},
		},
	}
	res, err := c.Exec("query", []driver.Value{123})
	if res != nil {
		t.Error("Result should be nil")
	}
	if err == nil {
		t.Error("error should not be nil")
	}
	pattern := regexp.MustCompile(regexp.QuoteMeta("all expectations were already fulfilled, call to exec"))
	if !pattern.MatchString(err.Error()) {
		t.Errorf("error should match expected error message (actual: %s)", err.Error())
	}
}
开发者ID:brunoqc,项目名称:go-sqlmock,代码行数:27,代码来源:connection_test.go


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