Search code examples
regexstringgorune

Regex-change substring to uppercase in a string golang


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("(?i)"+searchkey)//make searchkey case insensitive
     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)//rights back to the file
   }

Solution

  • You should use regexp for that, a simple example:

    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)
        })
    }
    

    //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
    }