正则表达式-将字符串中的子字符串转换为大写字母(使用Golang)

huangapple go评论69阅读模式
英文:

Regex-change substring to uppercase in a string golang

问题

我需要将一个字符串替换为同样单词的大写形式。到目前为止,我可以从包含我的字符串的文本文件中搜索子字符串,并将单词替换为"APPLE",例如"apple"、"Apple"或"ApPle"。问题出现在字符串是"Is that pineapple Apple adamsApple applepie smell?"时,我的搜索关键字存在于其他单词之间,因此无法找到并转换。

我的最终工作代码:

//从目录中获取txt文件并搜索单词
func fileRead(getPath string, searchkey string) {
var count int
buf1, _ := ioutil.ReadFile(getPath)
var buf2 = string(buf1)
var b string
tokens := strings.Fields(buf2)
re := regexp.MustCompile("(?i)" + searchkey) //使搜索关键字不区分大小写
for i := 0; i < len(tokens); i++ {
if strings.EqualFold(tokens[i], searchkey) {
tokens[i] = re.ReplaceAllString(tokens[i], strings.ToUpper(searchkey))
count++
} else {
tokens[i] = re.ReplaceAllLiteralString(tokens[i], strings.ToUpper(searchkey))
count++
}
}
for j := 0; j < len(tokens); j++ {
b += tokens[j]
b += " "
}
c := []byte(b)
fmt.Println(count, " ", getPath)
ioutil.WriteFile(getPath, c, 0644) //将结果写回文件
}

英文:

I need to replace a string with a uppercase of the same word.So far i can search for sub-string from a text file which contains my string and replace a word like "apple" or "Apple" or "ApPle" to "APPLE". The problem exist when the string is "Is that pineapple Apple adamsApple applepie smell?", my search keyword exist between the other word so it cannot be found and converted.

MY final working code:

 //Get the txt file from the directory and search for word
  func  fileRead(getPath  string,  searchkey  string){
    var  count  int
    buf1,_:=ioutil.ReadFile(getPath);
    var  buf2=  string(buf1)
    var  b  string
    tokens:=strings.Fields(buf2)
    re := regexp.MustCompile(&quot;(?i)&quot;+searchkey)//make searchkey case insensitive
     for  i:=0;i&lt;len(tokens);i++{
        		
      if  (strings.EqualFold(tokens[i],searchkey)){
        			
      tokens[i] = re.ReplaceAllString(tokens[i], strings.ToUpper(searchkey))
      count++
        			
     }else{

      tokens[i]=re.ReplaceAllLiteralString(tokens[i],strings.ToUpper(searchkey))
      count++
         }
        }
        for  j:=0;  j&lt;len(tokens);  j++{
         b+=  tokens[j]
         b+=&quot;  &quot;  
          }
        c  :=  []byte(b)
        fmt.Println(count,&quot;                  &quot;,getPath)
        ioutil.WriteFile(getPath,  c,  0644)//rights back to the file
   }

答案1

得分: 3

你应该使用正则表达式来实现,这是一个简单的示例:

func KeywordsToUpper(src string, keywords ...string) string {
    var re = regexp.MustCompile(`\b(` + strings.Join(keywords, "|") + `)\b`)
    return re.ReplaceAllStringFunc(src, func(w string) string {
        return strings.ToUpper(w)
    })
}

//编辑

我想我误解了问题,如果你只是想替换一个单词,即使它在其他单词中间,比如 myapplecomputer,那么使用 strings.Replace 应该就足够了,例如:

func ReplaceLikeYouDontCare(src string, words ...string) string {
    for _, w := range words {
        src = strings.Replace(src, w, strings.ToUpper(w), -1)
    }
    return src
}
英文:

You should use regexp for that, a simple example:

func KeywordsToUpper(src string, keywords ...string) string {
	var re = regexp.MustCompile(`\b(` + strings.Join(keywords, &quot;|&quot;) + `)\b`)
	return re.ReplaceAllStringFunc(src, func(w string) string {
		return strings.ToUpper(w)
	})
}

//edit

I think I misunderstood the question, if all you want is to replace a word even if it's in the middle of other words, like myapplecomputer then using strings.Replace should be enough, for example:

func ReplaceLikeYouDontCare(src string, words ...string) string {
	for _, w := range words {
		src = strings.Replace(src, w, strings.ToUpper(w), -1)
	}
	return src
}

答案2

得分: 1

不是strings.Replace正是你要找的吗?

func fileRead(getPath string, searchkey string) {
    buf, _ := ioutil.ReadFile(getPath)
    strings.Replace(string(buf), searchkey, strings.ToUpper(searchkey), -1)
}
英文:

Isn't strings.Replace exactly what you're looking for?

func fileRead(getPath string, searchkey string) {
    buf, _ := ioutil.ReadFile(getPath)
    strings.Replace(string(buf), searchkey, strings.ToUpper(searchkey), -1)
}

huangapple
  • 本文由 发表于 2014年7月18日 01:33:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/24809992.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定