Search⌘ K
AI Features

The regexp Package

Explore how to use Go's regexp package to perform regular expression searches, test patterns, and replace substrings in text. Understand functions like Match, Compile, and ReplaceAllString, and practice applying regex to manipulate phone number formats. This lesson equips you with essential skills to handle regex-based text processing efficiently in Go.

We'll cover the following...

Overview

Package regexp implements regular expression search. For information about regular expressions and their syntax, visit this page.

Explanation

Go (1.6.2)
package main
import (
"fmt"
"regexp"
"strconv"
)
func main() {
searchIn := "John: 2578.34 William: 4567.23 Steve: 5632.18" // string to search
pat := "[0-9]+.[0-9]+" // pattern search in searchIn
f := func (s string) string {
v, _ := strconv.ParseFloat(s, 32)
return strconv.FormatFloat(v * 2, 'f', 2, 32)
}
if ok, _ := regexp.Match(pat, []byte(searchIn)); ok {
fmt.Println("Match found!")
}
re, _ := regexp.Compile(pat)
str := re.ReplaceAllString(searchIn, "##.#") // replace pat with "##.#"
fmt.Println(str)
// using a function
str2 := re.ReplaceAllStringFunc(searchIn, f)
fmt.Println(str2)
}

In the code above, outside main at line 4, we import the package regexp. We want to search a string pattern pat ...