The Go Cookbook

A community built and contributed collection of practical recipes for real world Golang development.

View project on GitHub

Detecting a Substring

How do I determine if a string contains another string or pattern?

Go prides itself on being a low level language with a rich set of functionality included by default via the standard packages. The strings package is a great example of this.

Detecting Substrings

  • strings.Contains
  • strings.ContainsAny
  • strings.HasPrefix
  • strings.HasSuffix
test_substrings.go
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Contains("Assume", "Ass"))

	fmt.Println(strings.ContainsAny("team", "i"))
	fmt.Println(strings.ContainsAny("Hello", "aeiou&y"))

	fmt.Println(strings.HasPrefix("Hello World", "Hello"))
	fmt.Println(strings.HasSuffix("Hello World", "World"))
}
$ go run test_substrings.go
true
false
true
true
true

Detecting Patterns

test_regexp.go
package main

import (
	"fmt"
	"regexp"
)

func main() {
	matched, err := regexp.MatchString("Wor.*", "Hello World")
	fmt.Println("Matched:", matched, "Error:", err)
	matched, err = regexp.MatchString("Good.*", "Hello World")
	fmt.Println("Matched:", matched, "Error:", err)
	matched, err = regexp.MatchString("(bad regexp", "Hello World")
	fmt.Println("Matched:", matched, "Error:", err)
}
$ go run test_regexp.go
Matched: true Error: <nil>
Matched: false Error: <nil>
Matched: false Error: error parsing regexp: missing closing ): `(bad regexp`

Finding Matched Strings

test_returned_regexp.go
package main

import "fmt"

func main() {
	fmt.Println("unimplemented")
}
$ go run test_returned_regexp.go

Detecting Patterns that Include Special Characters

test_safe_regexp.go
package main

import "fmt"

func main() {
	fmt.Println("unimplemented")
}
$ go run test_safe_regexp.go

Precompiling Regular Expressions

  • regexp.Compile
  • regexp.MustCompile
test_precompiled_regexp.go
package main

import "fmt"

func main() {
	fmt.Println("unimplemented")
}
$ go run test_precompiled_regexp.go