2009-11-15 58 views
1

我不熟悉類C語法,並且想編寫代碼來找到&替換,例如,在源字符串中替換所有'A'到'B',用Regexp包替換AllAll或ReplaceAllString函數說'ABBA'?如何設置Regexp,src和repl類型?下面是的replaceAll code snippet從轉到文檔:如何使用Regexp包的ReplaceAll函數替換Go中的某個字符?

// ReplaceAll returns a copy of src in which all matches for the Regexp 
// have been replaced by repl. No support is provided for expressions 
// (e.g. \1 or $1) in the replacement text. 
func (re *Regexp) ReplaceAll(src, repl []byte) []byte { 
    lastMatchEnd := 0; // end position of the most recent match 
    searchPos := 0; // position where we next look for a match 
    buf := new(bytes.Buffer); 
    for searchPos <= len(src) { 
     a := re.doExecute("", src, searchPos); 
     if len(a) == 0 { 
      break // no more matches 
     }

// Copy the unmatched characters before this match. buf.Write(src[lastMatchEnd:a[0]]); // Now insert a copy of the replacement string, but not for a // match of the empty string immediately after another match. // (Otherwise, we get double replacement for patterns that // match both empty and nonempty strings.) if a[1] > lastMatchEnd || a[0] == 0 { buf.Write(repl) } lastMatchEnd = a[1]; // Advance past this match; always advance at least one character. _, width := utf8.DecodeRune(src[searchPos:len(src)]); if searchPos+width > a[1] { searchPos += width } else if searchPos+1 > a[1] { // This clause is only needed at the end of the input // string. In that case, DecodeRuneInString returns width=0. searchPos++ } else { searchPos = a[1] } } // Copy the unmatched characters after the last match. buf.Write(src[lastMatchEnd:len(src)]); return buf.Bytes();

}

回答

3

這是一個常規的做你想要什麼:

package main 
import ("fmt"; "regexp"; "os"; "strings";); 
func main() { 
    reg, error := regexp.Compile ("B"); 
    if error != nil { 
     fmt.Printf ("Compile failed: %s", error.String()); 
     os.Exit (1); 
    } 
    output := string (reg.ReplaceAll (strings.Bytes ("ABBA"), 
         strings.Bytes ("A"))); 
    fmt.Println (output); 
} 
+0

我怎麼能處理2周更換一次:A-> B,B-> A,所以ABBA變成BAAB在1步? – user211499 2009-11-16 21:18:12

+0

你爲什麼問我,而不是你接受答案的人? – 2009-11-17 04:48:22

+0

拍,我在這裏是新手,甚至不知道我只能接受1個答案,並接受了兩個答案,因爲我嘗試了他們,他們的工作。 – user211499 2009-11-17 10:12:42

1

這裏是一個小例子。您還可以找到他的好例子Regexp test class

package main 

import (
    "fmt" 
    "regexp" 
    "strings" 
) 

func main() { 
    re, _ := regexp.Compile("e") 
    input := "hello" 
    replacement := "a" 
    actual := string(re.ReplaceAll(strings.Bytes(input), strings.Bytes(replacement))) 
    fmt.Printf("new pattern %s", actual) 
} 
+0

'string()'是我所需要的。 – 2009-11-16 01:13:09

+0

strings.Bytes似乎並沒有像go1.7那樣工作。我不得不使用'actual:= string(re.ReplaceAll([] byte(input),[] byte(replacement)))'' – Bharat 2017-01-27 21:09:15

相關問題