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


Golang strings.NewReplacer函數代碼示例

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


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

示例1: CreateDockerfile

// Create in the temp dir a Dockerfile proper to the exec type
func CreateDockerfile(tmp_dir_path string, new_exec_path string, exec_file_name string, category categorization) (imageName string) {

	imageName_arrays := strings.SplitN(exec_file_name, ".", -1)
	imageName = imageName_arrays[0]

	execPathDest := fmt.Sprintf("bin/%s", exec_file_name)
	entryPoint := fmt.Sprintf("bin/%s", exec_file_name)

	// cp the templates/Dockerfile into the tmp dir
	newDockerfilePath := tmp_dir_path + "/Dockerfile"

	// read new Dockerfile
	DockerfileString := T_GENERIC

	// replace the placeholders to build the acutal Dockerfile
	replaceBaseImage := strings.NewReplacer("<BASE_IMAGE>", category.baseDockerImage)
	DockerfileStringReplaced := replaceBaseImage.Replace(DockerfileString)

	replaceExecPathSrc := strings.NewReplacer("<EXEC_PATH_SRC>", exec_file_name)
	DockerfileStringReplaced = replaceExecPathSrc.Replace(DockerfileStringReplaced)

	replaceExecPathDest := strings.NewReplacer("<EXEC_PATH_DEST>", execPathDest)
	DockerfileStringReplaced = replaceExecPathDest.Replace(DockerfileStringReplaced)

	replaceEntrypoint := strings.NewReplacer("<ENTRYPOINT>", entryPoint)
	DockerfileStringReplaced = replaceEntrypoint.Replace(DockerfileStringReplaced)

	// write in the Dockerfile the actual content with replaced values
	DockerfileBytesReplaced := []byte(DockerfileStringReplaced)
	err2 := ioutil.WriteFile(newDockerfilePath, DockerfileBytesReplaced, 0644)
	check(err2)

	return
}
開發者ID:zanhsieh,項目名稱:pipes,代碼行數:35,代碼來源:builder.go

示例2: darwinRelink

// darwinRelink makes paths of linked libraries relative to executable.
//
//   /usr/local/Cellar/qt5/5.3.0/lib/QtWidgets.framework/Versions/5/QtWidgets
//   /usr/local/opt/qt5/lib/QtWidgets.framework/Versions/5/QtWidgets
//   ->
//   @executable_path/../Frameworks/QtWidgets.framework/Versions/5/QtWidgets
func darwinRelink(qlib, name string, strict bool) (err error) {
	file, err := macho.Open(name)
	if err != nil {
		return
	}
	defer file.Close()
	libs, err := file.ImportedLibraries()
	if err != nil {
		return
	}
	var qlib2 string
	// detect alternative qlib (homebrew symlinks Qt to /usr/local/opt)
	for _, lib := range libs {
		idx := strings.Index(lib, "QtCore")
		if idx > 0 {
			qlib2 = lib[:idx-1] // drop sep
			break
		}
	}
	replacer := strings.NewReplacer(qlib, relinkBase, qlib2, relinkBase)
	if len(qlib2) < 1 && strict {
		return fmt.Errorf("darwin relink: corrupt binary: %s", name)
	} else if !strict {
		replacer = strings.NewReplacer(qlib, relinkBase)
	}
	// replace qlib/qlib2 to relinkBase
	for _, lib := range libs {
		rlib := replacer.Replace(lib)
		cmd := exec.Command("install_name_tool", "-change", lib, rlib, name)
		if err = cmd.Run(); err != nil {
			return fmt.Errorf("darwin relink: %v", err)
		}
	}
	return
}
開發者ID:GeertJohan,項目名稱:qml-kit,代碼行數:41,代碼來源:deploy_task.go

示例3: Configure

// Configure initializes this formatter with values from a plugin config.
func (format *CollectdToInflux10) Configure(conf core.PluginConfig) error {
	plugin, err := core.NewPluginWithType(conf.GetString("CollectdToInflux1009", "format.Forward"), conf)
	if err != nil {
		return err
	}
	format.base = plugin.(core.Formatter)
	format.tagString = strings.NewReplacer(",", "\\,", " ", "\\ ")
	format.stringString = strings.NewReplacer("\"", "\\\"")
	return nil
}
開發者ID:pombredanne,項目名稱:gollum-1,代碼行數:11,代碼來源:collectdtoinflux10.go

示例4: stripAndCrop

// Strips html markup, then limits to 280 characters. If the original text was
// longer than 280 chars, an ellipsis is appended.
func stripAndCrop(content string) string {
	content = processString(content,
		strings.NewReplacer("\n", " ").Replace,
		strings.NewReplacer("  ", " ").Replace,
		strings.TrimSpace,
		html.UnescapeString,
		html.UnescapeString,
		sanitize.HTML)

	if len(content) <= 280 {
		return content
	}

	return strings.TrimSpace(content[0:279]) + "…"
}
開發者ID:hawx,項目名稱:riviera,代碼行數:17,代碼來源:mapping.go

示例5: isMatch

func isMatch(s1, s2 string) bool {

	// Return immediate failure for empty value.
	if s1 == "" {
		return false
	}

	// Return immediate success for wildcard.
	if s2 == "*" {
		return true
	}

	// Make case-insensitive
	s1 = strings.ToLower(s1)
	s2 = strings.ToLower(s2)

	// Return immediate success for full match (case-insensitive).
	if s1 == s2 {
		return true
	}

	// Replace ":", ";", "," and "/" chars with whitespace.
	// Split s1 into whitespace separated fields.
	r := strings.NewReplacer(":", " ", ";", " ", ",", " ", "/", " ")
	fields := strings.Fields(r.Replace(s1))

	// Adjust any wildcards.
	if strings.ContainsAny(s2, "?*") {
		r := strings.NewReplacer("?", ".?", "*", ".*")
		s2 = r.Replace(s2)
	}

	// Default return value.
	retval := false

	// Create the regexp match checker (type *regexp.Regexp).
	checkMatch := regexp.MustCompile(s2)

	// Match the search term (s2) against each of s1's fields.
	for _, field := range fields {
		if checkMatch.MatchString(field) {
			retval = true
			break
		}
	}

	return retval
}
開發者ID:JamManolo,項目名稱:cavemode,代碼行數:48,代碼來源:searchUtils.go

示例6: init

func init() {
	var commonInitialismsForReplacer []string
	for _, initialism := range commonInitialisms {
		commonInitialismsForReplacer = append(commonInitialismsForReplacer, initialism, strings.Title(strings.ToLower(initialism)))
	}
	commonInitialismsReplacer = strings.NewReplacer(commonInitialismsForReplacer...)
}
開發者ID:lue828,項目名稱:osinstall-server,代碼行數:7,代碼來源:utils.go

示例7: postsHandler

func postsHandler(w http.ResponseWriter, r *http.Request, title string) {
	log.Print("Title is: " + title)
	log.Print(len(strings.Split(title, "/")))
	if len(strings.Split(title, "/")) > 2 {
		p, err := loadPage(title+".html", config.RootDesc, config.SiteName)
		if err != nil {
			log.Print(err)
			http.Redirect(w, r, "/", http.StatusFound)
			return
		}
		renderTemplate(w, "root", p)
	} else {
		r := strings.NewReplacer("_", " ")
		var data bytes.Buffer
		for i := len(posts) - 1; i >= 0; i-- {
			s := posts[i]
			row := fmt.Sprintf("<p><a href=\"/%s\">%s</a>\n\t\t\t\t<span class=\"blog-post-meta\">%s</span>\n\t\t\t\t</p>\n",
				strings.Split(s, ".html")[0], r.Replace(strings.Split(filepath.Base(s), ".html")[0]), dateFromPath(s))
			log.Print(s)
			data.Write([]byte(row))
		}
		p := &Page{SiteName: config.SiteName, PageTitle: "blargh", Body: template.HTML(data.String()), PostDate: "N/A", PostTitle: "plupp", Description: config.PostsDesc}
		renderTemplate(w, "posts", p)
	}
}
開發者ID:rbjorklin,項目名稱:simple-go-blog,代碼行數:25,代碼來源:webserver.go

示例8: parserPkg

func parserPkg(pkgRealpath, pkgpath string) error {
	rep := strings.NewReplacer("/", "_", ".", "_")
	commentFilename = COMMENTFL + rep.Replace(pkgpath) + ".go"
	if !compareFile(pkgRealpath) {
		Info(pkgRealpath + " has not changed, not reloading")
		return nil
	}
	genInfoList = make(map[string][]ControllerComments)
	fileSet := token.NewFileSet()
	astPkgs, err := parser.ParseDir(fileSet, pkgRealpath, func(info os.FileInfo) bool {
		name := info.Name()
		return !info.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go")
	}, parser.ParseComments)

	if err != nil {
		return err
	}
	for _, pkg := range astPkgs {
		for _, fl := range pkg.Files {
			for _, d := range fl.Decls {
				switch specDecl := d.(type) {
				case *ast.FuncDecl:
					if specDecl.Recv != nil {
						parserComments(specDecl.Doc, specDecl.Name.String(), fmt.Sprint(specDecl.Recv.List[0].Type.(*ast.StarExpr).X), pkgpath)
					}
				}
			}
		}
	}
	genRouterCode()
	savetoFile(pkgRealpath)
	return nil
}
開發者ID:jiajie999,項目名稱:beego,代碼行數:33,代碼來源:parser.go

示例9: escape

func (ttb *tosTCByte) escape() []canonTOSTCByteRecord {
	trs := make([]canonTOSTCByteRecord, len(ttb.Records))
	sr := strings.NewReplacer(
		"Capable", "",
		"(", "",
		")", "",
		"+", "",
		"-", "",
		"/", "",
		".", "",
		" ", "",
	)
	for i, tr := range ttb.Records {
		s := strings.TrimSpace(tr.Keyword)
		trs[i].OrigKeyword = s
		ss := strings.Split(s, " ")
		if len(ss) > 1 {
			trs[i].Keyword = strings.Join(ss[1:], " ")
		} else {
			trs[i].Keyword = ss[0]
		}
		trs[i].Keyword = sr.Replace(trs[i].Keyword)
		n, err := strconv.ParseUint(tr.Binary, 2, 8)
		if err != nil {
			continue
		}
		trs[i].Value = int(n)
	}
	return trs
}
開發者ID:EPICPaaS,項目名稱:go.net,代碼行數:30,代碼來源:gentest.go

示例10: CMD

func CMD(c *cli.Context) {
	checkCache(c)

	args := c.Args().First()

	hosts := []string{}

	for name, ip := range allNodes() {
		hosts = append(hosts, name, ip)
	}

	r := strings.NewReplacer(hosts...)
	argsWithIPs := fmt.Sprintf(r.Replace(args))

	parts := strings.Split(argsWithIPs, " ")

	cmd := exec.Command(parts[0], parts[1:]...)
	cmd.Stdout = stdout
	cmd.Stdin = os.Stdin

	err := cmd.Run()

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}
開發者ID:adamenger,項目名稱:rv,代碼行數:27,代碼來源:actions.go

示例11: split

// Prepares strings by splitting by caps, spaces, dashes, and underscore
func split(str string) (words []string) {
	repl := strings.NewReplacer(
		"@", "At ",
		"&", "And ",
		"|", "Pipe ",
		"$", "Dollar ",
		"!", "Bang ",
		"-", " ",
		"_", " ",
	)

	rex1 := regexp.MustCompile(`(\p{Lu})`)
	rex2 := regexp.MustCompile(`(\pL|\pM|\pN|\p{Pc})+`)

	str = trim(str)

	// Convert dash and underscore to spaces
	str = repl.Replace(str)

	// Split when uppercase is found (needed for Snake)
	str = rex1.ReplaceAllString(str, " $1")
	// check if consecutive single char things make up an initialism

	for _, k := range initialisms {
		str = strings.Replace(str, rex1.ReplaceAllString(k, " $1"), " "+k, -1)
	}
	// Get the final list of words
	words = rex2.FindAllString(str, -1)

	return
}
開發者ID:jak-atx,項目名稱:vic,代碼行數:32,代碼來源:util.go

示例12: ToJSON

func (b ServiceBroker) ToJSON() string {
	bytes, err := ioutil.ReadFile(assets.NewAssets().ServiceBroker + "/cats.json")
	Expect(err).To(BeNil())

	replacer := strings.NewReplacer(
		"<fake-service>", b.Service.Name,
		"<fake-service-guid>", b.Service.ID,
		"<dashboard-client-key>", b.Service.DashboardClient.Key,
		"<sso-test>", b.Service.DashboardClient.ID,
		"<sso-secret>", b.Service.DashboardClient.Secret,
		"<sso-redirect-uri>", b.Service.DashboardClient.RedirectUri,
		"<fake-plan>", b.SyncPlans[0].Name,
		"<fake-plan-guid>", b.SyncPlans[0].ID,
		"<fake-plan-2>", b.SyncPlans[1].Name,
		"<fake-plan-2-guid>", b.SyncPlans[1].ID,
		"<fake-async-plan>", b.AsyncPlans[0].Name,
		"<fake-async-plan-guid>", b.AsyncPlans[0].ID,
		"<fake-async-plan-2>", b.AsyncPlans[1].Name,
		"<fake-async-plan-2-guid>", b.AsyncPlans[1].ID,
		"<fake-sso-plan>", b.SsoPlans[0].Name,
		"<fake-sso-plan-guid>", b.SsoPlans[0].ID,
		"<sso-plan-client-id>", b.SsoPlans[0].DashboardClient.ID,
		"<sso-plan-secret>", b.SsoPlans[0].DashboardClient.Secret,
	)

	return replacer.Replace(string(bytes))
}
開發者ID:naheedmk,項目名稱:cf-acceptance-tests,代碼行數:27,代碼來源:broker.go

示例13: TestRead_TildePath

func TestRead_TildePath(t *testing.T) {
	isPath := true
	home, err := homedir.Dir()
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	f, cleanup := testTempFile(t, home)
	defer cleanup()

	if _, err := io.WriteString(f, "foobar"); err != nil {
		t.Fatalf("err: %s", err)
	}
	f.Close()

	r := strings.NewReplacer(home, "~")
	homePath := r.Replace(f.Name())
	contents, wasPath, err := Read(homePath)

	if err != nil {
		t.Fatalf("err: %s", err)
	}
	if wasPath != isPath {
		t.Fatalf("expected wasPath: %t, got %t", isPath, wasPath)
	}
	if contents != "foobar" {
		t.Fatalf("expected contents %s, got %s", "foobar", contents)
	}
}
開發者ID:AssertSelenium,項目名稱:terraform,代碼行數:28,代碼來源:read_test.go

示例14: markdownEscape

func markdownEscape(s string) string {
	return strings.NewReplacer(
		"_", "\\_",
		"*", "\\*",
		"[", "\\[",
	).Replace(s)
}
開發者ID:ghw,項目名稱:telegram-chinese-groups,代碼行數:7,代碼來源:helper.go

示例15: logMagFormat

//	格式化日誌信息
func logMagFormat(format string, msg *LogMsg) string {

	if nil == msg {
		return ""
	}
	if 0 == len(format) {
		format = "${yyyy}-${MM}-${dd} ${hh}:${mm}:${ss}${SSSSSS} [${TARGET}] ([${LOG_GROUP}][${LOG_TAG}][L${FILE_LINE} ${FUNC_NAME}])\n${MSG}"
	}

	//	格式化時間
	format = SFTimeUtil.YMDHMSSSignFormat(msg.dateTime, format)

	//	日誌的格式化信息,別隨意更換順序,因為根據設計來進行日誌信息的格式化操作
	logFormat := []string{
		"${LOG_GROUP}", msg.logGroup,
		"${LOG_TAG}", msg.logTag,
		"${FILE_LINE}", strconv.Itoa(msg.fileLine),
		"${FILE_PATH}", msg.filePath,
		"${FUNC_NAME}", msg.funcName,
		"${STACK}", msg.stack,
		"${TARGET}", string(msg.target),
		"${MSG}", msg.msg,
	}

	replacer := strings.NewReplacer(logFormat...)

	return replacer.Replace(format)
}
開發者ID:slowfei,項目名稱:gosfcore,代碼行數:29,代碼來源:SFLog.go


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