Golang Regexp Examples: MatchString, MustCompile

Use the regexp package for regular expressions. Call MatchString and compile patterns.

Regexp. 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 use Compile to create reusable objects.

MatchString example. This program uses the MatchString method without first creating a Regexp instance. This means that a compiled expression is not reused.
Pattern: We use some metacharacters in the pattern. The period means "any character" and the plus means "one or more."
Result: The first return value (matched) is a boolean that is true if the pattern matched. The second is an error value (which may be nil).
Golang program that uses regexp.MatchString 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) } } Output true

Compile regexp. A 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: This method compiles a regular expression and returns the instance. It will cause an error (panic) if the pattern is invalid.
Here: We loop over the strings in a slice and attempt to match each string with the compiled regular expression.
Golang program that compiles regexp and uses MatchString 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) } } Output cat100 = true dog200 = true bird = false 200fish = false

Split. This method is called on a regexp instance. We first compile the delimiter pattern (specified as a regular expression). Each substring is separated based on matches of this pattern.
Argument 1: This is the string we want to split. This should have delimiters (like commas or spaces).
Argument 2: The second argument to Split() is the maximum number of substrings to get. We use a negative number to indicate no limit.
Golang program that uses Split, regexp package main import ( "fmt" "regexp" ) func main() { value := "carrot,cat;dog" // Compile the delimiter as a regular expression. re := regexp.MustCompile(`\W`) // Call split based on the delimiter pattern. // ... Get all substrings. result := re.Split(value, -1) // Display our results. for i := range(result) { fmt.Println(result[i]) } } Output carrot cat dog

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.Find

A summary. The regexp package is a prized feature in Go. Unlike older languages like Perl, Go uses more advanced logic to compile and execute these text programs.

© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.