本文整理汇总了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
}
示例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
}
示例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
}
示例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]) + "…"
}
示例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
}
示例6: init
func init() {
var commonInitialismsForReplacer []string
for _, initialism := range commonInitialisms {
commonInitialismsForReplacer = append(commonInitialismsForReplacer, initialism, strings.Title(strings.ToLower(initialism)))
}
commonInitialismsReplacer = strings.NewReplacer(commonInitialismsForReplacer...)
}
示例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)
}
}
示例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
}
示例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
}
示例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)
}
}
示例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
}
示例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))
}
示例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)
}
}
示例14: markdownEscape
func markdownEscape(s string) string {
return strings.NewReplacer(
"_", "\\_",
"*", "\\*",
"[", "\\[",
).Replace(s)
}
示例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)
}