MatchString
In Go, we find an optimized regular expression engine. This runs in linear time, making complex patterns faster. It is located in the regexp
package.
With MatchString
, we see if a pattern can match a string
. This tells us if the string
satisfies the pattern's requirements. We can use Match
to try to find a match within a byte slice.
MatchString
exampleThis program uses the MatchString
method without first creating a Regexp
instance. This means that a compiled expression is not reused.
nil
).package main
import (
"fmt"
"regexp"
)
func main() {
value := "cat"
// See if this regular expression matches.
matched, _ := regexp.MatchString(".+t", value)
// Test the result.
if matched {
fmt.Println(true)
}
}true
MustCompile
exampleA regexp
can be compiled. Once compiled, it can be reused many times with no delays before calls. Many methods, like MatchString
are available on regexp
instances.
MustCompile()
compiles a regular expression and returns the instance. It will cause an error (panic) if the pattern is invalid.string
with the compiled regular expression.package main import ( "fmt" "regexp" ) func main() { // Compile this regular expression. var lettersDigits = regexp.MustCompile(`\w\w\w\d\d\d`) // Some strings to test. values := []string{"cat100", "dog200", "bird", "200fish"} // Loop over our strings and call MatchString on them. for i := range values { result := lettersDigits.MatchString(values[i]) fmt.Printf("%v = %v\n", values[i], result) } }cat100 = true dog200 = true bird = false 200fish = false
Match
Unlike the MatchString
method, Match()
operates on a byte slice. We can convert a string
literal to a byte slice to test the Match
func
.
package main
import (
"fmt"
"regexp"
)
func main() {
// With Match, we must match a byte slice, not a string.
text := []byte("bird is Blue")
re := regexp.MustCompile(`[bB]..e`)
// Returns true because Blue matches the pattern.
hasMatch := re.Match(text)
fmt.Println(hasMatch)
}true
Find
, FindAllString
With Find()
and other methods like FindAllString()
, a search is performed before matching occurs. So the entire string
does not need to match—only parts do.
The regexp
package is a key feature in Go. To achieve top performance, Go uses advanced logic to compile and execute these text programs.