Golang: Regular Expression

By Xah Lee. Date: . Last updated: .

Example: Check If String Match

package main

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

func main() {
	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

package main

// 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?».`

func main() {
	var re = regexp.MustCompile(`(?i:alice)`)
	var replaceStr = "Mary"
	var result = re.ReplaceAllLiteralString(longtext, replaceStr)
	fmt.Printf("%v\n", result)
}

Reference

https://golang.org/pkg/regexp/

Golang, String