packagemain// find a regex in string, print its begin/end index
import"fmt"import"regexp"var mytext = `Alice was beginning to get very tired of sitting by her`funcmain() {
var re = regexp.MustCompile(`(?i:was)`)
var matchIndexes = re.FindStringIndex(mytext)
if matchIndexes == nil {
fmt.Printf("not found\n")
} else {
fmt.Printf("match indexes at %v\n", matchIndexes)
}
// match indexes at [6 9]
}
Example: find and replace text
packagemain// replace Alice by Mary
import"fmt"import"regexp"var longtext = `Alice was beginning to get very tired of sitting by her
sister on the bank, and of having nothing to do: once or twice she had
peeped into the book her sister was reading, but it had no pictures or
conversations in it, «and what is the use of a book,» thought Alice «without
pictures or conversation?».`funcmain() {
var re = regexp.MustCompile(`(?i:alice)`)
var replaceStr = "Mary"var result = re.ReplaceAllLiteralString(longtext, replaceStr)
fmt.Printf("%v\n", result)
}