2009-11-15 11 views
1

Je ne suis pas familier avec les syntaxes C-like et aimerais écrire le code pour trouver & remplacer, disons, tous les 'A à' B dans une chaîne source, disons 'ABBA' avec le paquet Regexp fonctions ReplaceAll ou ReplaceAllString? Comment puis-je configurer Regexp type, src et repl? Voici la code snippet ReplaceAll de la documentation Go:Comment remplacer un caractère dans Go en utilisant la fonction ReplaceAll du paquet Regexp?

// 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();

}

Répondre

3

Ceci est une routine pour faire ce que vous voulez:

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

comment puis-je gérer 2 remplacements à la fois: A> B, B-> A, alors ABBA se transforme en BAAB en 1 étape? – user211499

+0

Pourquoi m'as-tu demandé à la place du type dont tu as accepté la réponse? –

+0

shoot, je suis tellement novice ici, je ne savais même pas que je ne pouvais accepter qu'une seule réponse sur plusieurs et accepté les deux réponses que je les ai essayé et ils ont travaillé. – user211499

1

Voici un petit exemple. Vous pouvez également trouver de bons exemples, il 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()' est ce dont j'avais besoin. –

+0

strings.Bytes ne semble pas fonctionner à partir de go1.7. Je devais utiliser 'effective: = string (re.ReplaceAll ([] byte (entrée), [] byte (remplacement)))' – Bharat