Golang Regexp Examples: MatchString, MustCompileUse 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) } }
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) } }
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]) } }
carrot cat dog
Replace. We can replace strings using a pattern with regex in Golang as well. Here is some sample code from the Golang program that generates this website.
Info We want to replace a string pattern starting with the word "stage" with a string ending with the word "compress."
Tip We use the meta code $1 to reference the captured group after the word "stage," and place it in the result of ReplaceAllString.
Golang program that uses ReplaceAllString
package main import ( "fmt" "regexp" ) func main() { // Input string. input := "/programs/stage-perls/" // Change a string starting with "stage" into a string ending with "compress." re := regexp.MustCompile(`stage-([a-z]*)`) replacementResult := re.ReplaceAllString(input, "stage-$1-compress") // Before and after. fmt.Println(input) fmt.Println(replacementResult) }
/programs/stage-perls/ /programs/stage-perls-compress/
$1 The captured group ([a-z]*)
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.
A summary. The regexp package is a key feature in Go. To achieve top performance, Go uses advanced logic to compile and execute these text programs.
© 2007-2021 sam allen. see site info on the changelog