Go offers built-in support for regular expressions. Here are some examples of common regexp-related tasks in Go. |
|
package main
|
|
import "bytes"
import "fmt"
import "regexp"
|
|
func main() {
|
|
This tests whether a pattern matches a string. |
match, _ := regexp.MatchString("p([a-z]+)ch", "peach")
fmt.Println(match)
|
Above we used a string pattern directly, but for
other regexp tasks you’ll need to |
r, _ := regexp.Compile("p([a-z]+)ch")
|
Many methods are available on these structs. Here’s a match test like we saw earlier. |
fmt.Println(r.MatchString("peach"))
|
This finds the match for the regexp. |
fmt.Println(r.FindString("peach punch"))
|
The also finds the first match but returns the start and end indexes for the match instead of the matching text. |
fmt.Println(r.FindStringIndex("peach punch"))
|
The |
fmt.Println(r.FindStringSubmatch("peach punch"))
|
Similarly this will return information about the indexes of matches and submatches. |
fmt.Println(r.FindStringSubmatchIndex("peach punch"))
|
The |
fmt.Println(r.FindAllString("peach punch pinch", -1))
|
These |
fmt.Println(r.FindAllStringSubmatchIndex(
"peach punch pinch", -1))
|
Providing a non-negative integer as the second argument to these functions will limit the number of matches. |
fmt.Println(r.FindAllString("peach punch pinch", 2))
|
Our examples above had string arguments and used
names like |
fmt.Println(r.Match([]byte("peach")))
|
When creating constants with regular expressions
you can use the |
r = regexp.MustCompile("p([a-z]+)ch")
fmt.Println(r)
|
The |
fmt.Println(r.ReplaceAllString("a peach", "<fruit>"))
|
The |
in := []byte("a peach")
out := r.ReplaceAllFunc(in, bytes.ToUpper)
fmt.Println(string(out))
}
|
$ go run regular-expressions.go
true
true
peach
[0 5]
[peach ea]
[0 5 1 3]
[peach punch pinch]
[[0 5 1 3] [6 11 7 9] [12 17 13 15]]
[peach punch]
true
p([a-z]+)ch
a <fruit>
a PEACH
|
|
For a complete reference on Go regular expressions check
the |
Previous example: String Formatting.
Next example: JSON.