Regular Expressions
// Importing necessary packages.
import (
"bytes"
"fmt"
"regexp"
)
// The main function, where the execution of the program begins.
func main() {
// Using MatchString to check if a string matches a regular expression pattern.
match, _ := regexp.MatchString("p([a-z]+)ch", "peach")
fmt.Println(match)
// Compiling a regular expression pattern for reuse.
r, _ := regexp.Compile("p([a-z]+)ch")
// Using MatchString with the compiled regex.
fmt.Println(r.MatchString("peach"))
// Finding the first match in the input string.
fmt.Println(r.FindString("peach punch"))
// Finding the start and end indices of the first match.
fmt.Println("idx:", r.FindStringIndex("peach punch"))
// Finding submatches of the first match.
fmt.Println(r.FindStringSubmatch("peach punch"))
// Finding start and end indices of submatches of the first match.
fmt.Println(r.FindStringSubmatchIndex("peach punch"))
// Finding all matches in the input string.
fmt.Println(r.FindAllString("peach punch pinch", -1))
// Finding all start and end indices of submatches in all matches.
fmt.Println("all:", r.FindAllStringSubmatchIndex(
"peach punch pinch", -1))
// Finding a specific number of matches.
fmt.Println(r.FindAllString("peach punch pinch", 2))
// Matching using a byte slice.
fmt.Println(r.Match([]byte("peach")))
// Compiling a regular expression using MustCompile for simplicity.
r = regexp.MustCompile("p([a-z]+)ch")
fmt.Println("regexp:", r)
// Replacing all matches with a specified string.
fmt.Println(r.ReplaceAllString("a peach", "<fruit>"))
// Replacing all matches using a function.
in := []byte("a peach")
out := r.ReplaceAllFunc(in, bytes.ToUpper)
fmt.Println(string(out))
}Output
Last updated